#!/usr/bin/env python3
"""CLI entry for the schema-selected full reading copy Markdown renderer.

Usage:
    python3 scripts/okstra-render-final-report.py \\
        <data.json> \\
        [--output <final-report.md>] \\
        [--template <path>]

When ``--output`` is omitted, derives the markdown sibling by stripping
the ``.data.json`` suffix and appending ``.md``. The render is idempotent
under data.json mutations and intentionally overwrites any existing
output — the markdown is regenerated whenever the data.json changes
(Phase 7 token substitution, re-renders).
"""
from __future__ import annotations

import argparse
import sys
from pathlib import Path

_HERE = Path(__file__).resolve().parent
# Make ``okstra_ctl`` and ``okstra_vendor`` importable when running from
# repo (``scripts/`` is the parent of these packages). The installed
# runtime adds ``~/.okstra/lib/python`` to PYTHONPATH via the wrapper
# scripts; for in-repo invocation we add ``scripts/`` explicitly.
sys.path.insert(0, str(_HERE))

from okstra_ctl.final_report_paths import final_report_markdown_path  # noqa: E402
from okstra_ctl.render_final_report import (  # noqa: E402
    FinalReportRenderError,
    render_to_file,
    snapshot_last_valid,
)


def main(argv: list[str]) -> int:
    parser = argparse.ArgumentParser(
        description="Render a final-report markdown from its JSON SSOT.",
    )
    parser.add_argument(
        "data",
        type=Path,
        help="Path to the final-report data.json (the JSON SSOT).",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=None,
        help=(
            "Output markdown path. Defaults to the data.json sibling "
            "with the `.data.json` suffix stripped and `.md` appended."
        ),
    )
    parser.add_argument(
        "--template",
        type=Path,
        default=None,
        help=(
            "Optional override for the Jinja2 template file. By default, "
            "data.json.schemaVersion selects the matching installed or "
            "repo-local report template."
        ),
    )
    args = parser.parse_args(argv)

    output = args.output or final_report_markdown_path(args.data)

    try:
        bytes_written = render_to_file(
            args.data,
            output,
            template_path=args.template,
        )
    except FinalReportRenderError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1

    snapshot_last_valid(args.data)
    print(f"wrote {bytes_written} bytes -> {output}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
