#!/usr/bin/env python3
"""Render latest 1C saved-state watch run lookup 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 code(value: Any) -> str:
    if value is None:
        return "`null`"
    return f"`{value}`"


def render_run(run: dict[str, Any]) -> str:
    counts = run.get("counts") or {}
    out = ""
    out += bullet(f"Run: {code(run.get('run'))}")
    out += bullet(f"Run dir: {code(run.get('run_dir'))}")
    out += bullet(f"Manifest check passed: {code(run.get('manifest_check_passed'))}")
    out += bullet(f"Delta check passed: {code(run.get('delta_check_passed'))}")
    out += bullet(
        "Counts: "
        f"objects={code(counts.get('object_changes'))}, "
        f"systems={code(counts.get('system_changes'))}, "
        f"delta_added={code(counts.get('delta_objects_added'))}, "
        f"delta_removed={code(counts.get('delta_objects_removed'))}, "
        f"delta_changed={code(counts.get('delta_objects_changed'))}, "
        f"delta_unchanged={code(counts.get('delta_objects_unchanged'))}"
    )
    for key in ("manifest_markdown", "markdown", "delta_markdown", "report", "delta"):
        if run.get(key):
            out += bullet(f"{key}: {code(run.get(key))}")
    return out


def render(data: dict[str, Any]) -> str:
    counts = data.get("counts") or {}
    safety = data.get("safety") or {}
    out = ""
    out += line("# 1C Latest Saved State Watch Run")
    out += line()
    out += line(f"Output root: `{data.get('output_root')}`")
    out += line(f"Require delta: `{data.get('require_delta')}`")
    out += line(f"Require changed: `{data.get('require_changed')}`")
    out += line(f"Found: `{data.get('found')}`")
    out += line()
    out += line("## History Counts")
    out += bullet(f"Runs: `{counts.get('runs')}`")
    out += bullet(f"With delta: `{counts.get('with_delta')}`")
    out += bullet(f"With delta changes: `{counts.get('with_delta_changes')}`")

    latest = data.get("latest")
    if latest:
        out += line()
        out += line("## Latest")
        out += render_run(latest)

    out += line()
    out += line("## Safety")
    for key in ("read_only", "sql_write_performed"):
        out += bullet(f"{key}: `{safety.get(key)}`")
    return out


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

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