from __future__ import annotations

import argparse
import json
import sys

from .init_tool import init_security_context
from .validation import validate_context_file


def main_validate() -> None:
    parser = argparse.ArgumentParser(description="Validate security-context.yaml")
    parser.add_argument(
        "context_path",
        nargs="?",
        default="security-context.yaml",
        help="Path to security-context.yaml",
    )
    parser.add_argument(
        "--schema",
        dest="schema_path",
        default=None,
        help="Path to security-context.schema.json",
    )
    args = parser.parse_args()

    report = validate_context_file(context_path=args.context_path, schema_path=args.schema_path)
    payload = {
        "valid": report.valid,
        "errors": report.errors,
        "warnings": report.warnings,
        "context_path": args.context_path,
    }
    print(json.dumps(payload, indent=2))
    raise SystemExit(0 if report.valid else 1)


def main_init() -> None:
    parser = argparse.ArgumentParser(
        description="Generate a security-context.yaml from a threat model.",
    )
    parser.add_argument("threat_model_path", help="Path to threat model text/markdown file")
    parser.add_argument(
        "--output",
        dest="output_path",
        default="security-context.yaml",
        help="Output security context path",
    )
    parser.add_argument("--project-name", default=None, help="Optional project name")
    parser.add_argument(
        "--no-llm",
        action="store_true",
        help="Disable Claude-assisted generation and use heuristic mapping only.",
    )
    parser.add_argument(
        "--model",
        dest="llm_model",
        default="claude-3-5-sonnet-latest",
        help="Claude model to use for aegis_init.",
    )
    parser.add_argument(
        "--schema",
        dest="schema_path",
        default=None,
        help="Path to security-context.schema.json",
    )
    args = parser.parse_args()

    result = init_security_context(
        threat_model_path=args.threat_model_path,
        output_path=args.output_path,
        project_name=args.project_name,
        use_llm=not args.no_llm,
        llm_model=args.llm_model,
        schema_path=args.schema_path,
    )
    print(json.dumps(result, indent=2))
    raise SystemExit(0 if result["ok"] else 1)


if __name__ == "__main__":
    command = sys.argv[1] if len(sys.argv) > 1 else ""
    if command == "validate":
        sys.argv.pop(1)
        main_validate()
    elif command == "init":
        sys.argv.pop(1)
        main_init()
    else:
        print("Usage: python -m aegis.cli [validate|init] ...")
        raise SystemExit(2)
