"""
eaigins_sdk CLI
───────────────
Command-line interface for the Eaigins SDK.

Commands:
    eaigins validate   — run a quick self-test of the governance pipeline
    eaigins evaluate   — evaluate a JSON action file against a domain
    eaigins export     — export a sample audit trail JSON
    eaigins version    — print SDK version
"""

import argparse
import json
import sys


def cmd_version(args):
    from eaigins_sdk import __version__
    print(f"eaigins-sdk {__version__}")


def cmd_validate(args):
    """Run a quick self-test: all three domains, 3 actions each."""
    from eaigins_sdk import ControlPlane, AgentAction
    from eaigins_sdk.policies import AML_POLICIES, HEALTHCARE_POLICIES, CUSTOMERCARE_POLICIES

    print("Eaigins SDK — self-test\n" + "="*50)
    all_ok = True

    test_cases = [
        ("Financial / AML",   AML_POLICIES,         "crewai::aml-agent",
         [("query_sanctions_db",   {"customer_id":"C-001"},         ["public_sanctions_list"],  "ALLOW"),
          ("file_sar",             {"case_id":"CASE-001"},           ["compliance_reports"],     "BLOCK"),
          ("get_transaction_history", {"account_id":"ALL","limit":50000}, ["transaction_history"], "BLOCK")]),
        ("Healthcare",        HEALTHCARE_POLICIES,  "langchain::clinical-agent",
         [("add_chart_note",      {"patient_id":"P-001"},           ["patient_vitals"],         "ALLOW"),
          ("dispense_medication", {"drug":"Metformin"},              ["patient_ehr"],            "BLOCK"),
          ("export_patient_data", {"destination":"external_research_db","patient_count":340}, ["patient_ehr"], "BLOCK")]),
        ("Customer Care",     CUSTOMERCARE_POLICIES,"autogen::cx-agent",
         [("get_order_status",    {"order_id":"ORD-001"},           ["order_management_db"],    "ALLOW"),
          ("delete_customer_account", {"verified":False},           ["crm_customer_profile"],   "BLOCK"),
          ("apply_bulk_discount", {"estimated_cost":285000,"discount_percent":40,"customer_count":8400}, ["order_management_db"], "BLOCK")]),
    ]

    for domain, policies, agent, cases in test_cases:
        cp = ControlPlane(policies=policies)
        print(f"\n[{domain}]")
        for tool, params, sources, expected in cases:
            action = AgentAction(
                agent_id=agent, prompt=f"Test: {tool}", tool_name=tool,
                tool_params=params, context_sources=sources,
            )
            d = cp.evaluate(action)
            ok = d.decision.value == expected
            status = "✓" if ok else "✗"
            print(f"  {status} {tool:<40} expected={expected:<8} got={d.decision.value}")
            if not ok:
                all_ok = False

    print("\n" + "="*50)
    if all_ok:
        print("✅ All tests passed — SDK is working correctly.")
    else:
        print("✗  Some tests failed — check output above.")
        sys.exit(1)


def cmd_evaluate(args):
    """Evaluate a JSON action file against a named policy set."""
    import os
    from eaigins_sdk import ControlPlane, AgentAction
    from eaigins_sdk.policies import AML_POLICIES, HEALTHCARE_POLICIES, CUSTOMERCARE_POLICIES

    POLICY_MAP = {
        "financial":    AML_POLICIES,
        "healthcare":   HEALTHCARE_POLICIES,
        "customercare": CUSTOMERCARE_POLICIES,
    }

    if not os.path.isfile(args.action_file):
        print(f"Error: file not found: {args.action_file}", file=sys.stderr)
        sys.exit(1)

    with open(args.action_file) as f:
        data = json.load(f)

    policies = POLICY_MAP.get(args.domain)
    if policies is None:
        print(f"Error: unknown domain '{args.domain}'. Choose: {list(POLICY_MAP)}", file=sys.stderr)
        sys.exit(1)

    cp     = ControlPlane(policies=policies)
    action = AgentAction(**data)
    d      = cp.evaluate(action)

    print(json.dumps(d.to_dict(), indent=2))
    sys.exit(0 if d.allowed else 1)


def cmd_export(args):
    """Generate and print a sample audit trail."""
    from eaigins_sdk import ControlPlane, AgentAction
    from eaigins_sdk.policies import AML_POLICIES

    cp = ControlPlane(policies=AML_POLICIES)
    for tool, params, sources in [
        ("query_sanctions_db",  {"customer_id":"C-001","lists":["OFAC"]}, ["public_sanctions_list"]),
        ("file_sar",            {"case_id":"CASE-001"},                   ["compliance_reports"]),
        ("send_to_external_api",{"endpoint":"https://ext.io"},            ["transaction_history"]),
    ]:
        action = AgentAction(
            agent_id="sample-agent", prompt=f"Demo: {tool}",
            tool_name=tool, tool_params=params, context_sources=sources,
        )
        cp.evaluate(action)

    print(cp.export_audit_json())


def main():
    parser = argparse.ArgumentParser(
        prog="eaigins",
        description="Eaigins Enterprise AI Control Plane SDK",
    )
    sub = parser.add_subparsers(dest="command")

    sub.add_parser("version",  help="Print SDK version")
    sub.add_parser("validate", help="Run SDK self-test")

    p_eval = sub.add_parser("evaluate", help="Evaluate a JSON action file")
    p_eval.add_argument("action_file", help="Path to JSON file with AgentAction fields")
    p_eval.add_argument("--domain", default="financial",
                        help="Policy domain: financial|healthcare|customercare")

    sub.add_parser("export", help="Print a sample audit trail JSON")

    args = parser.parse_args()

    dispatch = {
        "version":  cmd_version,
        "validate": cmd_validate,
        "evaluate": cmd_evaluate,
        "export":   cmd_export,
    }

    fn = dispatch.get(args.command)
    if fn is None:
        parser.print_help()
        sys.exit(0)
    fn(args)


if __name__ == "__main__":
    main()
