#!/usr/bin/env python3
"""Render 1C extension validation release check 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())
    status = f" status=`{gate.get('status')}`" if gate.get("status") is not None else ""
    suffix = f" {summary}" if summary else ""
    return bullet(f"`{gate.get('name')}` passed=`{gate.get('passed')}`{status}{suffix}")


def render_findings(findings: list[dict[str, Any]]) -> str:
    out = ""
    for finding in findings:
        path = f" path=`{finding.get('path')}`" if finding.get("path") else ""
        out += bullet(f"{finding.get('severity')} `{finding.get('code')}` - {finding.get('message')}{path}")
    return out


def render(data: dict[str, Any]) -> str:
    out = ""
    out += line("# 1C Extension Validation Release")
    out += line()
    out += line(f"Status: `{data.get('status')}`")
    out += line(f"Passed: `{data.get('passed')}`")
    out += line(f"Preferred extension: `{data.get('preferred_extension')}`")
    out += line(f"Staging: `{data.get('staging_dir')}`")
    out += line(f"Bundle: `{data.get('bundle_dir')}`")
    out += line()
    out += line("## Safety")
    safety = data.get("safety") or {}
    for key in ("production_apply_allowed", "automatic_apply_allowed", "human_approval_required"):
        out += bullet(f"{key}: `{safety.get(key)}`")
    out += line()
    out += line("## Gates")
    for gate in data.get("gates") or []:
        out += render_gate(gate)
    if data.get("findings"):
        out += line()
        out += line("## Findings")
        out += render_findings(data.get("findings") or [])
    evidence_findings = (((data.get("details") or {}).get("validation_evidence_check") or {}).get("findings") or [])
    if evidence_findings:
        out += line()
        out += line("## Evidence Findings")
        out += render_findings(evidence_findings)
    out += line()
    out += line("## Next Actions")
    for action in data.get("next_actions") or []:
        out += bullet(action)
    return out


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

    markdown = render(load_json(args.release_check))
    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())
