from __future__ import annotations

import argparse
from pathlib import Path


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Run requirement-code consistency comparison.")
    parser.add_argument("--srs-extraction-id", type=int, required=True)
    parser.add_argument("--vector-path", required=True)
    parser.add_argument("--metadata-path", required=True)
    parser.add_argument("--graph-path", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--output-excel", default=None)
    parser.add_argument("--output-markdown", default=None)
    parser.add_argument("--top-k", type=int, default=8)
    parser.add_argument("--max-call-hops", type=int, default=2)
    parser.add_argument("--min-similarity", type=float, default=0.55)
    parser.add_argument("--no-llm", action="store_true")
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    from app.db.session import SessionLocal
    from app.models.tooling import SRSRequirement
    from app.services.code_kb.adapter import CodeKnowledgeBaseAdapter
    from app.services.consistency.comparator import ConsistencyComparator
    from app.services.consistency.exporter import export_excel, export_json, export_markdown

    adapter = CodeKnowledgeBaseAdapter()
    adapter.load(args.vector_path, args.metadata_path, args.graph_path)
    comparator = ConsistencyComparator(adapter, use_llm=not args.no_llm)

    db = SessionLocal()
    try:
        requirements = (
            db.query(SRSRequirement)
            .filter(SRSRequirement.extraction_id == args.srs_extraction_id)
            .order_by(SRSRequirement.sort_order)
            .all()
        )
        results = comparator.compare_requirements(
            requirements,
            top_k=args.top_k,
            max_call_hops=args.max_call_hops,
            min_similarity=args.min_similarity,
        )
    finally:
        db.close()

    Path(args.output).write_bytes(export_json(results))
    if args.output_markdown:
        Path(args.output_markdown).write_text(export_markdown(results), encoding="utf-8")
    if args.output_excel:
        Path(args.output_excel).write_bytes(export_excel(results))
    return 0


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