#!/usr/bin/env python3
"""Convert script_doctor_brief.json → revision editor annotation format.

Reads [project]/state/script_doctor_brief.json and outputs
[project]/state/script_doctor_annotations.json in the format expected
by the revision editor's auto-load feature.

Usage:
    python3 convert_annotations.py <project>
"""

import json
import sys
import time
from pathlib import Path

# Resolve project root
SCRIPT_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = SCRIPT_DIR.parent.parent


def convert(project: str) -> dict:
    """Convert script doctor brief to revision editor annotations."""
    brief_path = PROJECT_ROOT / project / "state" / "script_doctor_brief.json"
    if not brief_path.is_file():
        print(f"ERROR: {brief_path} not found", file=sys.stderr)
        sys.exit(1)

    try:
        with open(brief_path) as f:
            brief = json.load(f)
    except json.JSONDecodeError as e:
        print(f"ERROR: Invalid JSON in {brief_path}: {e}", file=sys.stderr)
        sys.exit(1)

    generated = brief.get("generated", "")
    annotations = []
    ts = int(time.time() * 1000)

    for finding in brief.get("findings", []):
        fid = finding["id"]
        severity = finding.get("severity", "P3")
        dimension = finding.get("dimension", "unknown")
        title = finding.get("title", "")

        for ann in finding.get("annotations", []):
            ts += 1
            annotations.append({
                "id": f"ann_{ts}",
                "episode": ann["episode"],
                "line_start": ann.get("line", 0),
                "line_end": ann.get("line", 0),
                "selected_text": ann.get("selected_text", ""),
                "action": ann.get("action", "FLAG"),
                "comment": ann.get("note", ""),
                "finding_id": fid,
                "severity": severity,
                "dimension": dimension,
                "finding_title": title,
                "created_at": generated,
            })

    # Summary
    by_action = {}
    by_severity = {}
    by_dimension = {}
    for a in annotations:
        by_action[a["action"]] = by_action.get(a["action"], 0) + 1
        by_severity[a["severity"]] = by_severity.get(a["severity"], 0) + 1
        by_dimension[a["dimension"]] = by_dimension.get(a["dimension"], 0) + 1

    # Find fountain file
    project_dir = PROJECT_ROOT / project
    fountain_files = sorted(project_dir.glob("*.fountain"))
    source_file = fountain_files[0].name if fountain_files else f"{project.upper()}_COMPLETE.fountain"

    result = {
        "source_file": source_file,
        "project": project,
        "generated_from": "script_doctor_brief.json",
        "annotations": annotations,
        "summary": {
            "total": len(annotations),
            "by_action": by_action,
            "by_severity": by_severity,
            "by_dimension": by_dimension,
        },
    }

    return result


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 convert_annotations.py <project>", file=sys.stderr)
        sys.exit(1)

    project = sys.argv[1]
    result = convert(project)

    out_path = PROJECT_ROOT / project / "state" / "script_doctor_annotations.json"
    out_path.parent.mkdir(parents=True, exist_ok=True)

    with open(out_path, "w") as f:
        json.dump(result, f, indent=2)

    total = result["summary"]["total"]
    print(f"Converted {total} annotations → {out_path.relative_to(PROJECT_ROOT)}")
    print(f"  Actions: {result['summary']['by_action']}")
    print(f"  Severity: {result['summary']['by_severity']}")
    print(f"  Dimensions: {result['summary']['by_dimension']}")


if __name__ == "__main__":
    main()
