"""런타임 계약 그래프 검증 명령 진입점."""
from __future__ import annotations

import argparse
import json
from pathlib import Path
import sys

from .contract_graph import (
    ContractFile,
    ContractGraphError,
    ContractGraphRoot,
    ContractGraphValidator,
    ContractSelection,
)


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="okstra contract-check",
        description="Validate runtime contract documents and dependencies.",
    )
    parser.add_argument("--root", required=True, type=Path)
    selection = parser.add_mutually_exclusive_group()
    selection.add_argument("--profile")
    selection.add_argument("--operation")
    return parser


def _record(row: ContractFile) -> dict[str, str]:
    return {
        "path": row.relative_path,
        "schemaVersion": row.schema_version,
        "sha256": row.sha256,
    }


def main(argv: list[str] | None = None) -> int:
    args = _parser().parse_args(argv)
    selected = None
    if args.profile is not None or args.operation is not None:
        selected = ContractSelection(args.profile, args.operation)
    try:
        graph = ContractGraphValidator().validate(
            ContractGraphRoot.from_base(args.root), selected=selected
        )
        if args.profile is not None:
            rows = graph.dependencies_for_profile(args.profile)
        elif args.operation is not None:
            rows = graph.dependencies_for_operation(args.operation)
        else:
            rows = graph.files
    except ContractGraphError as exc:
        for error in exc.errors:
            print(error, file=sys.stderr)
        return 1
    print(json.dumps([_record(row) for row in rows], indent=2))
    return 0


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