from __future__ import annotations

import cProfile
import hashlib
import json
import os
import pstats
import sqlite3
import time
from pathlib import Path

from jarvis_finance.services.household_import import preview_household_import

DB = Path("/home/agent/jarvis_runtime/finance-system/data/finance.sqlite3")
PAYLOAD = Path("/home/agent/jarvis_runtime/finance-system/sprint16.1-uat/real-preview-payload-private.json")
ROOT = Path("/home/agent/jarvis_runtime/finance-system/sprint16.3-analysis")
PROFILE = ROOT / "baseline-preview-profile-private.prof"
SUMMARY = ROOT / "baseline-preview-profile-private.json"
SOURCES = [
    Path("/home/agent/.hermes/private/finance/sprint16") / name
    for name in ("raiffeisen.csv", "akb_transactions.csv", "visa.csv", "migros.csv")
]


def sha_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def private_json(path: Path, value: object) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + ".tmp")
    tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2))
    os.chmod(tmp, 0o600)
    os.replace(tmp, path)
    os.chmod(path, 0o600)


def main() -> None:
    ROOT.mkdir(parents=True, exist_ok=True)
    os.chmod(ROOT, 0o700)
    source_before = {str(path): sha_file(path) for path in SOURCES}
    payload = json.loads(PAYLOAD.read_text())
    conn = sqlite3.connect(f"file:{DB}?mode=ro", uri=True)
    conn.row_factory = sqlite3.Row
    profiler = cProfile.Profile()
    started = time.perf_counter()
    profiler.enable()
    result = preview_household_import(conn, payload)
    profiler.disable()
    elapsed = time.perf_counter() - started
    conn.close()
    profiler.dump_stats(PROFILE)
    os.chmod(PROFILE, 0o600)
    stats = pstats.Stats(profiler)
    rows = []
    for (filename, line, function), (_, calls, total, cumulative, _) in sorted(
        stats.stats.items(), key=lambda item: item[1][3], reverse=True
    )[:80]:
        rows.append({
            "module": Path(filename).name,
            "line": line,
            "function": function,
            "calls": calls,
            "self_seconds": round(total, 6),
            "cumulative_seconds": round(cumulative, 6),
        })
    summary = {
        "base_sha": "9e08547043fbe667cb102c3d3fdae8cdef05245f",
        "elapsed_seconds": round(elapsed, 6),
        "source_hashes_unchanged": source_before == {str(path): sha_file(path) for path in SOURCES},
        "counts": result.get("counts"),
        "review_threshold": result.get("review_threshold"),
        "preview_fingerprint": result.get("preview_fingerprint"),
        "input_fingerprint": result.get("input_fingerprint"),
        "business_ready_for_confirm": result.get("business_ready_for_confirm"),
        "top_functions": rows,
        "confirm_called": False,
    }
    private_json(SUMMARY, summary)
    print(json.dumps({
        "elapsed_seconds": summary["elapsed_seconds"],
        "counts": summary["counts"],
        "review_threshold": summary["review_threshold"],
        "source_hashes_unchanged": summary["source_hashes_unchanged"],
        "business_ready_for_confirm": summary["business_ready_for_confirm"],
        "profile": str(PROFILE),
        "summary": str(SUMMARY),
        "modes": [oct(PROFILE.stat().st_mode & 0o777), oct(SUMMARY.stat().st_mode & 0o777)],
        "confirm_called": False,
    }, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
