#!/usr/bin/env python3
"""Render 1C saved-state watch run list 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 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 += line(f"### {run.get('run')}")
    out += bullet(f"Database: {code(run.get('database'))}")
    out += bullet(f"Run dir: {code(run.get('run_dir'))}")
    out += bullet(f"Manifest check: {code(run.get('manifest_check_passed'))}")
    out += bullet(f"Delta check: {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'))}"
    )
    if run.get("manifest_markdown"):
        out += bullet(f"Watch markdown: {code(run.get('manifest_markdown'))}")
    if run.get("delta_markdown"):
        out += bullet(f"Delta markdown: {code(run.get('delta_markdown'))}")
    if run.get("markdown"):
        out += bullet(f"Report markdown: {code(run.get('markdown'))}")
    if run.get("error"):
        out += bullet(f"Error: {code(run.get('error'))}")
    out += line()
    return out


def render(data: dict[str, Any]) -> str:
    counts = data.get("counts") or {}
    filters = data.get("filters") or {}
    out = ""
    out += line("# 1C Saved State Watch Runs")
    out += line()
    out += line(f"Output root: `{data.get('output_root')}`")
    out += line()
    out += line("## Summary")
    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')}`")
    out += line()
    out += line("## Filters")
    for key in ("limit", "only_with_delta", "only_changed"):
        out += bullet(f"{key}: `{filters.get(key)}`")

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

    runs = data.get("runs") or []
    if runs:
        out += line()
        out += line("## Runs")
        for run in runs:
            out += render_run(run)

    safety = data.get("safety") or {}
    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 1C saved-state watch run list Markdown.")
    parser.add_argument("--list", type=Path, required=True)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()

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