#!/usr/bin/env python3
"""
Pramana CLI — Command-line verification tool.

Usage:
    python -m pramana.cli verify --data '{"cpu":0.9}' --constraints '{"cpu":0.85}'
    python -m pramana.cli action --type deploy --risk high
    python -m pramana.cli llm --output "some text" --format json
    python -m pramana.cli building --sqft 15000 --occupancy 200 --exits 2
    python -m pramana.cli serve --port 8108
"""

import argparse
import json
import sys

from pramana.core.engine import Pramana
from pramana.core.arthashastra import StrategicContext
from pramana.constraints.agent_safety import verify_llm_output
from pramana.constraints.construction import check_building_code


def cmd_verify(args):
    engine = Pramana()
    data = json.loads(args.data) if args.data else {}
    constraints = json.loads(args.constraints) if args.constraints else {}
    result = engine.verify_quick(data, constraints)
    _print_result(result)


def cmd_action(args):
    engine = Pramana()
    result = engine.verify_action(
        task_type=args.type,
        description=args.description or "",
        risk_level=args.risk or "medium",
        cost_usd=args.cost or 0.0,
        reversible=not args.irreversible,
    )
    _print_result(result)


def cmd_llm(args):
    output = args.output
    if args.file:
        with open(args.file) as f:
            output = f.read()
    result = verify_llm_output(
        output=output,
        expected_format=args.format,
        max_length=args.max_length,
        required_fields=args.required.split(",") if args.required else None,
        banned_patterns=args.banned.split(",") if args.banned else None,
    )
    _print_result(result)


def cmd_building(args):
    building = {
        "sqft": args.sqft,
        "occupancy": args.occupancy,
        "exits": args.exits,
        "sprinklers": args.sprinklers,
        "travel_distance_ft": args.travel_distance or 0,
        "accessible_entrances": args.accessible_entrances or 1,
    }
    if args.door_widths:
        building["door_widths"] = [int(w) for w in args.door_widths.split(",")]

    results = check_building_code(building, args.occupancy_type or "B")

    passed = sum(1 for r in results if r.passed)
    failed = sum(1 for r in results if not r.passed)
    all_violations = []
    for r in results:
        all_violations.extend(r.violations)

    print(f"\nBuilding Code Check: {passed} passed, {failed} failed")
    print(f"{'='*50}")
    for r in results:
        status = "PASS" if r.passed else "FAIL"
        print(f"  [{status}] {r.sutra}: {r.detail}")
        for v in r.violations:
            print(f"        ! {v}")
    if all_violations:
        print(f"\nTotal violations: {len(all_violations)}")
    else:
        print("\nAll checks passed.")


def cmd_serve(args):
    try:
        import uvicorn
        from pramana.api.server import create_app
        app = create_app()
        print(f"Pramana API starting on port {args.port}...")
        uvicorn.run(app, host=args.host, port=args.port)
    except ImportError:
        print("Install FastAPI: pip install fastapi uvicorn")
        sys.exit(1)


def _print_result(result):
    print(f"\nVerdict: {result.verdict}")
    print(f"Confidence: {result.confidence}")
    print(f"Reasoning:")
    for r in result.reasoning:
        print(f"  - {r}")

    if hasattr(result, 'to_dict'):
        d = result.to_dict()
        if "vedic" in d and d["vedic"].get("sutras"):
            print(f"\nSutra Details:")
            for s in d["vedic"]["sutras"]:
                status = "PASS" if s["passed"] else "FAIL"
                print(f"  [{status}] {s['sutra']}: {s['detail']}")
                for v in s.get("violations", []):
                    print(f"        ! {v}")
        if "strategy" in d:
            st = d["strategy"]
            print(f"\nStrategy:")
            print(f"  Posture: {st['posture']}")
            print(f"  Upaya: {st['upaya']}")
            print(f"  Risk: {st['risk_score']}")


def main():
    parser = argparse.ArgumentParser(
        prog="pramana",
        description="Pramana Engine — Vedic Verification for AI"
    )
    sub = parser.add_subparsers(dest="command")

    # verify
    p_verify = sub.add_parser("verify", help="Constraint verification")
    p_verify.add_argument("--data", help="JSON data to verify")
    p_verify.add_argument("--constraints", help="JSON constraints")

    # action
    p_action = sub.add_parser("action", help="Strategic action assessment")
    p_action.add_argument("--type", required=True, help="Action type")
    p_action.add_argument("--description", help="Action description")
    p_action.add_argument("--risk", help="Risk level: low/medium/high/critical")
    p_action.add_argument("--cost", type=float, help="Cost in USD")
    p_action.add_argument("--irreversible", action="store_true")

    # llm
    p_llm = sub.add_parser("llm", help="Verify LLM output")
    p_llm.add_argument("--output", help="LLM output text")
    p_llm.add_argument("--file", help="Read output from file")
    p_llm.add_argument("--format", help="Expected format (json)")
    p_llm.add_argument("--max-length", type=int, help="Max length")
    p_llm.add_argument("--required", help="Required fields (comma-sep)")
    p_llm.add_argument("--banned", help="Banned patterns (comma-sep)")

    # building
    p_bldg = sub.add_parser("building", help="Building code check")
    p_bldg.add_argument("--sqft", type=int, required=True)
    p_bldg.add_argument("--occupancy", type=int, required=True)
    p_bldg.add_argument("--exits", type=int, required=True)
    p_bldg.add_argument("--sprinklers", action="store_true")
    p_bldg.add_argument("--travel-distance", type=int)
    p_bldg.add_argument("--accessible-entrances", type=int)
    p_bldg.add_argument("--door-widths", help="Comma-separated inches")
    p_bldg.add_argument("--occupancy-type", help="IBC type (B, A-1, etc.)")

    # serve
    p_serve = sub.add_parser("serve", help="Start API server")
    p_serve.add_argument("--port", type=int, default=8108)
    p_serve.add_argument("--host", default="0.0.0.0")

    args = parser.parse_args()
    if not args.command:
        parser.print_help()
        sys.exit(0)

    cmds = {
        "verify": cmd_verify, "action": cmd_action,
        "llm": cmd_llm, "building": cmd_building, "serve": cmd_serve,
    }
    cmds[args.command](args)


if __name__ == "__main__":
    main()
