"""Command-line wrapper around src.validators.mindmodel_validator.validate_manifest

This tiny CLI loads a manifest and writes a structured JSON report to stdout
and optionally to a file path. It is report-only: it never raises an error or
changes exit code based on findings.
"""

from __future__ import annotations

import argparse
import json
import os
from pathlib import Path
from typing import Any


def _write_report(report: dict[str, Any], path: Path | None) -> None:
    text = json.dumps(report, indent=2, ensure_ascii=False)
    print(text)
    if path:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(text, encoding="utf-8")


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser("validate_mindmodel")
    parser.add_argument("manifest", nargs="?", help="path to manifest file")
    parser.add_argument("--manifest", dest="manifest_opt", help="path to manifest file")
    parser.add_argument("--report", help="optional output report path")
    args = parser.parse_args(argv)

    manifest = args.manifest_opt or args.manifest
    if not manifest:
        parser.error("manifest path is required (positional or --manifest)")

    # import here to keep CLI tiny when unused
    try:
        from src.validators.mindmodel_validator import validate_manifest
    except Exception as e:  # pragma: no cover - defensive
        print(f"Failed to import validator: {e}")
        return 0

    try:
        report = validate_manifest(manifest, report_only=True)
    except Exception as e:  # never fail the process
        report = {"error": str(e)}

    report_path = Path(args.report) if args.report else None
    _write_report(report, report_path)

    # always exit zero for report-only operation
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
