#!/usr/bin/env python3
"""Render 1C patch preflight JSON as Markdown."""

from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any


def load_json(path: Path) -> dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8-sig"))


def line(text: str = "") -> str:
    return text.rstrip() + "\n"


def bullet(text: str) -> str:
    return f"- {text}\n"


def render_gate(gate: dict[str, Any]) -> str:
    counts = gate.get("counts") or {}
    summary = ", ".join(f"{key}={value}" for key, value in counts.items())
    return bullet(f"`{gate.get('name')}` passed=`{gate.get('passed')}` {summary}")


def render(data: dict[str, Any]) -> str:
    out = ""
    out += line("# 1C Patch Preflight")
    out += line()
    out += line(f"Workspace: `{data.get('workspace')}`")
    out += line(f"Status: `{data.get('status')}`")
    out += line(f"Passed: `{data.get('passed')}`")
    out += line()
    out += line("## Gates")
    for gate in data.get("gates") or []:
        out += render_gate(gate)
    out += line()
    out += line("## Diff")
    diff = data.get("diff_summary") or {}
    for key in ("files", "modified", "unchanged", "missing", "added_lines", "removed_lines", "hunks"):
        out += bullet(f"{key}: `{diff.get(key)}`")
    out += line()
    out += line("## Next Actions")
    for action in data.get("next_actions") or []:
        out += bullet(action)
    findings = []
    for detail_name in ("safety", "integrity", "freshness", "semantic", "diff"):
        detail = (data.get("details") or {}).get(detail_name) or {}
        for finding in detail.get("findings") or []:
            findings.append((detail_name, finding))
    if findings:
        out += line()
        out += line("## Findings")
        for gate, finding in findings:
            out += bullet(f"`{gate}` {finding.get('severity')} `{finding.get('code')}` - {finding.get('message')}")
    return out


def main() -> int:
    parser = argparse.ArgumentParser(description="Render 1C patch preflight Markdown.")
    parser.add_argument("--preflight", type=Path, required=True)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()

    markdown = render(load_json(args.preflight))
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(markdown, encoding="utf-8")
        print(json.dumps({"output": str(args.output)}, ensure_ascii=False))
    else:
        print(markdown)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
