"""Read-only ownership recovery for Phase 5E.3 runtime findings."""

from __future__ import annotations

import json
import subprocess
from pathlib import Path

from src.domain.codegen.runtime_ownership import classify_runtime_file, content_fingerprint

ROOT = Path(__file__).parents[1]
CLONES = Path(r"C:\Users\Mohsin.Abbas\AppData\Local\Temp\p2hs-phase5a-e5220a3312ca4c9bb6ee8d8c17bca1ea")


def git(root: Path, *args: str) -> str:
    result = subprocess.run(["git", *args], cwd=root, text=True, capture_output=True, check=True)
    return result.stdout.strip()


def commits(root: Path, path: str) -> list[dict[str, str]]:
    raw = git(root, "log", "--follow", "--format=%H%x1f%h%x1f%s", "--", path)
    rows = []
    for line in reversed([item for item in raw.splitlines() if item.strip()]):
        full, short, subject = line.split("\x1f", 2)
        rows.append({"full": full, "short": short, "subject": subject})
    return rows


def main() -> None:
    inventory = json.loads((ROOT / "phase5d-migration-inventory.json").read_text(encoding="utf-8"))
    records = []
    for project in inventory["records"]:
        if not project["runtime_files"]:
            continue
        root = CLONES / f"p2hs-{project['project_id'].replace('-', '')}"
        for item in project["runtime_files"]:
            path = item["path"]
            if path.startswith(".p2hs/") or not (root / path).is_file():
                continue
            history = commits(root, path)
            if not history:
                records.append({"project_id": project["project_id"], "path": path, "ownership_class": "UNRESOLVED", "reason": "missing_git_history"})
                continue
            p2hs_history = all(
                "[p2hs]" in entry["subject"].lower()
                or "initial react_app boilerplate" in entry["subject"].lower()
                or "prepare project from discovery" in entry["subject"].lower()
                for entry in history
            )
            customer_history = any(not ("[p2hs]" in entry["subject"].lower() or "initial react_app boilerplate" in entry["subject"].lower() or "prepare project from discovery" in entry["subject"].lower()) for entry in history[1:])
            current_sha = git(root, "rev-parse", "HEAD:" + path)
            current_fp = content_fingerprint(root / path)
            origin = history[0]
            evidence = classify_runtime_file(
                path=path,
                origin_revision=origin["short"],
                origin_sha=origin["full"],
                origin_evidence="p2hs:" + origin["subject"] if p2hs_history else "git:" + origin["subject"],
                current_sha=current_sha,
                origin_fingerprint=None,
                current_fingerprint=current_fp,
                later_platform_change=p2hs_history and len(history) > 1,
                customer_change=(not p2hs_history) or customer_history,
            )
            records.append({
                "project_id": project["project_id"],
                "path": path,
                "ownership_class": evidence.ownership_class,
                "origin_revision": evidence.origin_revision,
                "origin_sha": evidence.origin_sha,
                "origin_evidence": evidence.origin_evidence,
                "current_sha": evidence.current_sha,
                "current_fingerprint": evidence.current_fingerprint,
                "modification_status": evidence.modification_status,
                "confidence": evidence.confidence,
                "history_count": len(history),
            })
    counts = {}
    for row in records:
        counts[row["ownership_class"]] = counts.get(row["ownership_class"], 0) + 1
    output = {"schema_version": "phase5e3.runtime-ownership.v1", "projects": len({row["project_id"] for row in records}), "files": len(records), "counts": counts, "records": records}
    (ROOT / "phase5e3-runtime-ownership.json").write_text(json.dumps(output, sort_keys=True, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"projects": output["projects"], "files": output["files"], "counts": counts}, sort_keys=True))


if __name__ == "__main__":
    main()
