#!/usr/bin/env python3
"""CLI entry for the top-of-report index / scroll-anchor injector.

Usage:
    python3 scripts/okstra-inject-report-index.py \\
        <final-report.md> \\
        [--report-language en|ko]

Adds the top-of-report Index (section list + ID index) and `<a id="...">`
scroll anchors to a markdown report that was authored *free-form* rather
than rendered from a data.json. The only such task-type today is
`improvement-discovery`: its `## 5.9 Improvement Candidates` table is
written directly by the report-writer worker, so the data.json renderer
(which injects the index for every other task-type) never sees it.

Idempotent — re-running on an already-indexed report is a no-op.
"""
from __future__ import annotations

import argparse
import sys
from pathlib import Path

_HERE = Path(__file__).resolve().parent
# Make ``okstra_ctl`` importable for in-repo invocation (the installed
# runtime adds ``~/.okstra/lib/python`` via the wrapper scripts).
sys.path.insert(0, str(_HERE))

from okstra_ctl.i18n import SUPPORTED_LANGS  # noqa: E402
from okstra_ctl.render_final_report import (  # noqa: E402
    FinalReportRenderError,
    inject_index_into_file,
)


def main(argv: list[str]) -> int:
    parser = argparse.ArgumentParser(
        description="Inject the top-of-report index + scroll anchors into a free-form markdown report.",
    )
    parser.add_argument(
        "report",
        type=Path,
        help="Path to the final-report markdown to rewrite in place.",
    )
    parser.add_argument(
        "--report-language",
        choices=list(SUPPORTED_LANGS),
        default="en",
        help="Language for the index labels (Index/목차, …). Default: en.",
    )
    args = parser.parse_args(argv)

    try:
        bytes_written = inject_index_into_file(
            args.report, report_language=args.report_language
        )
    except FinalReportRenderError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1

    print(f"injected index + anchors -> {args.report} ({bytes_written} bytes)")
    return 0


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