"""
eaigins_sdk.policies
────────────────────
Built-in governance policy sets for common enterprise domains.

Usage::

    from eaigins_sdk.policies import AML_POLICIES, HEALTHCARE_POLICIES, CUSTOMERCARE_POLICIES
    from eaigins_sdk.policy import PolicyGateway

    gw = PolicyGateway(policies=AML_POLICIES)
"""

from __future__ import annotations
from .policy import Policy


# ═════════════════════════════════════════════════════════════════════════════
# FINANCIAL SERVICES — AML / Fraud Investigation
# Frameworks: BSA · FATF · FinCEN · OFAC
# ═════════════════════════════════════════════════════════════════════════════

AML_POLICIES: list[Policy] = [

    Policy(
        policy_id="POL-001", category="OPERATIONAL",
        name="High-Value Transaction Approval",
        description="Transactions > $10,000 require compliance officer approval.",
        requires_human_approval=True, blocks_action=False,
        evaluate=lambda a: (
            a.tool_params.get("amount", 0) <= 10_000,
            f"Transaction ${a.tool_params.get('amount', 0):,} exceeds $10,000 — "
            "requires compliance officer approval.",
        ),
    ),

    Policy(
        policy_id="POL-002", category="REGULATORY",
        name="SAR Filing Authorization",
        description="SARs may only be filed by licensed compliance staff.",
        requires_human_approval=True, blocks_action=False,
        evaluate=lambda a: (
            a.tool_name not in {"file_sar", "submit_regulatory_report"},
            "SAR/regulatory filing requires human compliance officer authorization (FATF).",
        ),
    ),

    Policy(
        policy_id="POL-003", category="DATA_GOVERNANCE",
        name="Customer PII Data Access",
        description="Full PII access requires an active investigation case_id.",
        requires_human_approval=False, blocks_action=True,
        evaluate=lambda a: (
            not (a.tool_name == "get_customer_full_profile" and not a.tool_params.get("case_id")),
            "Full PII access requires case_id. Blocked per data governance policy.",
        ),
    ),

    Policy(
        policy_id="POL-004", category="DATA_GOVERNANCE",
        name="External Data Exfiltration Prevention",
        description="No enterprise data to external endpoints.",
        requires_human_approval=False, blocks_action=True,
        evaluate=lambda a: (
            a.tool_name not in {"send_to_external_api", "webhook_post", "email_external"},
            "Enterprise data export to external endpoints is blocked.",
        ),
    ),

    Policy(
        policy_id="POL-005", category="OPERATIONAL",
        name="Account Action Scope Limit",
        description="AI may flag accounts but cannot freeze/close them autonomously.",
        requires_human_approval=True, blocks_action=False,
        evaluate=lambda a: (
            a.tool_name not in {"freeze_account", "close_account", "block_customer"},
            "Account freeze/closure requires human authorization.",
        ),
    ),

    Policy(
        policy_id="POL-006", category="DATA_GOVERNANCE",
        name="Bulk Data Query Limit",
        description="Batch queries must not exceed 1,000 records.",
        requires_human_approval=False, blocks_action=True,
        evaluate=lambda a: (
            a.tool_params.get("limit", 100) <= 1_000,
            f"Bulk query limit exceeded: {a.tool_params.get('limit', 0)} > 1,000 records.",
        ),
    ),

    Policy(
        policy_id="POL-007", category="REGULATORY",
        name="Regulatory Framework Compliance",
        description="Investigation actions must cite a regulatory framework.",
        requires_human_approval=False, blocks_action=False,
        evaluate=lambda a: (
            bool(a.metadata.get("regulatory_framework")) or
            a.tool_name not in {"generate_investigation_report", "file_sar"},
            "Investigation reports must cite applicable regulatory framework (FATF/BSA).",
        ),
    ),
]


# ═════════════════════════════════════════════════════════════════════════════
# HEALTHCARE — Clinical Copilot
# Frameworks: HIPAA · FDA 21 CFR Part 11 · Joint Commission · HL7 FHIR
# ═════════════════════════════════════════════════════════════════════════════

HEALTHCARE_POLICIES: list[Policy] = [

    Policy(
        policy_id="HC-001", category="OPERATIONAL",
        name="Prescription Requires Physician Sign-off",
        description="AI may recommend but not dispense — physician approval required.",
        requires_human_approval=True, blocks_action=False,
        evaluate=lambda a: (
            a.tool_name not in {"dispense_medication", "submit_prescription"},
            "Prescription execution requires licensed physician approval (FDA 21 CFR).",
        ),
    ),

    Policy(
        policy_id="HC-002", category="OPERATIONAL",
        name="Diagnostic Test Ordering Authorization",
        description="Lab orders require attending physician authorization.",
        requires_human_approval=True, blocks_action=False,
        evaluate=lambda a: (
            a.tool_name != "order_diagnostic_test",
            "Diagnostic test orders require attending physician authorization (Joint Commission).",
        ),
    ),

    Policy(
        policy_id="HC-003", category="DATA_GOVERNANCE",
        name="Patient PHI Access Requires Session",
        description="PHI access needs active session_id (HIPAA).",
        requires_human_approval=False, blocks_action=True,
        evaluate=lambda a: (
            not (
                a.tool_name in {"get_patient_full_record", "export_patient_data"} and
                not a.tool_params.get("session_id") and
                not a.tool_params.get("guardian_consent", True)
            ),
            "Patient PHI access requires session_id (HIPAA 45 CFR §164.502).",
        ),
    ),

    Policy(
        policy_id="HC-004", category="OPERATIONAL",
        name="No Autonomous Medication Dispensing",
        description="Requires pharmacist + physician dual verification.",
        requires_human_approval=False, blocks_action=True,
        evaluate=lambda a: (
            a.tool_name != "dispense_medication",
            "Autonomous dispensing prohibited — dual verification required (FDA 21 CFR).",
        ),
    ),

    Policy(
        policy_id="HC-005", category="OPERATIONAL",
        name="Surgical Recommendation Requires Specialist",
        description="Surgical procedure recommendations need specialist review.",
        requires_human_approval=True, blocks_action=False,
        evaluate=lambda a: (
            not (
                a.tool_name == "generate_treatment_recommendation" and
                a.tool_params.get("recommendation_type") == "SURGICAL"
            ),
            "Surgical recommendations require specialist physician review.",
        ),
    ),

    Policy(
        policy_id="HC-006", category="DATA_GOVERNANCE",
        name="Patient Data External Transfer Prevention",
        description="No PHI to external destinations without IRB + DPA.",
        requires_human_approval=False, blocks_action=True,
        evaluate=lambda a: (
            not (
                a.tool_name in {"export_patient_data", "send_to_external_api"} and
                "external" in str(a.tool_params.get("destination", ""))
            ),
            "PHI export to external destination blocked — requires IRB approval (HIPAA/HITECH).",
        ),
    ),

    Policy(
        policy_id="HC-007", category="OPERATIONAL",
        name="Critical Medication Dose Change Limit",
        description="Autonomous dose changes are prohibited.",
        requires_human_approval=True, blocks_action=True,
        evaluate=lambda a: (
            a.tool_name != "update_medication_order",
            "Autonomous medication dose changes prohibited — physician review required.",
        ),
    ),

    Policy(
        policy_id="HC-008", category="DATA_GOVERNANCE",
        name="Minor Patient Data Protection",
        description="Minor psychiatric records require guardian consent.",
        requires_human_approval=False, blocks_action=True,
        evaluate=lambda a: (
            not (
                a.tool_params.get("include_psychiatric") and
                a.tool_params.get("guardian_consent") is False
            ),
            "Minor psychiatric record access requires guardian consent.",
        ),
    ),
]


# ═════════════════════════════════════════════════════════════════════════════
# CUSTOMER CARE — Enterprise Support Agent
# Frameworks: GDPR · CCPA · PCI-DSS · ISO 27001
# ═════════════════════════════════════════════════════════════════════════════

CUSTOMERCARE_POLICIES: list[Policy] = [

    Policy(
        policy_id="CX-001", category="OPERATIONAL",
        name="Refund Approval Threshold",
        description="Refunds > $200 require supervisor approval.",
        requires_human_approval=True, blocks_action=False,
        evaluate=lambda a: (
            not (a.tool_name == "process_refund" and a.tool_params.get("amount", 0) > 200),
            f"Refund ${a.tool_params.get('amount', 0)} exceeds $200 — supervisor approval required.",
        ),
    ),

    Policy(
        policy_id="CX-002", category="DATA_GOVERNANCE",
        name="Identity Verification for Account Changes",
        description="Payment/credential changes need verified identity (PCI-DSS).",
        requires_human_approval=False, blocks_action=True,
        evaluate=lambda a: (
            not (
                a.tool_name in {"update_payment_method", "change_account_password"} and
                not a.tool_params.get("identity_verified", False)
            ),
            "Account changes require verified identity (PCI-DSS Req. 8).",
        ),
    ),

    Policy(
        policy_id="CX-003", category="DATA_GOVERNANCE",
        name="Bulk Customer PII Export Prevention",
        description="Bulk PII export requires DPO approval (GDPR Art. 25).",
        requires_human_approval=False, blocks_action=True,
        evaluate=lambda a: (
            not (a.tool_name in {"export_customer_data", "send_to_external_api"} and
                 a.tool_params.get("include_pii")),
            "Bulk PII export requires DPO approval (GDPR Art. 25 / CCPA §1798.100).",
        ),
    ),

    Policy(
        policy_id="CX-004", category="OPERATIONAL",
        name="Account Deletion Verification Required",
        description="Erasure requests need secondary channel verification (GDPR Art. 17).",
        requires_human_approval=False, blocks_action=True,
        evaluate=lambda a: (
            not (a.tool_name == "delete_customer_account" and
                 not a.tool_params.get("verified", False)),
            "Account deletion requires verified identity confirmation (GDPR Art. 17).",
        ),
    ),

    Policy(
        policy_id="CX-005", category="OPERATIONAL",
        name="Mass Discount Financial Impact Limit",
        description="Bulk discounts with estimated cost > $10,000 require CFO approval.",
        requires_human_approval=True, blocks_action=True,
        evaluate=lambda a: (
            not (a.tool_name == "apply_bulk_discount" and
                 a.tool_params.get("estimated_cost", 0) > 10_000),
            f"Bulk discount cost ${a.tool_params.get('estimated_cost', 0):,} > $10,000 — CFO approval required.",
        ),
    ),

    Policy(
        policy_id="CX-006", category="OPERATIONAL",
        name="High-Value Loyalty Credit Approval",
        description="Credits > 1,000 points require team lead approval.",
        requires_human_approval=True, blocks_action=False,
        evaluate=lambda a: (
            not (a.tool_name == "apply_account_credits" and
                 a.tool_params.get("amount", 0) > 1_000),
            f"Credit adjustment {a.tool_params.get('amount', 0)} > 1,000 — team lead approval required.",
        ),
    ),

    Policy(
        policy_id="CX-007", category="OPERATIONAL",
        name="Account Closure with Balance Requires Human",
        description="Closure with outstanding balance requires human review.",
        requires_human_approval=True, blocks_action=False,
        evaluate=lambda a: (
            not (a.tool_name == "close_customer_account" and
                 a.tool_params.get("outstanding_balance", 0) > 0),
            f"Account closure with ${a.tool_params.get('outstanding_balance', 0)} balance requires human review.",
        ),
    ),

    Policy(
        policy_id="CX-008", category="DATA_GOVERNANCE",
        name="External Data Transfer Governance",
        description="External transfers need signed DPA (GDPR Art. 28).",
        requires_human_approval=False, blocks_action=True,
        evaluate=lambda a: (
            not (
                a.tool_name in {"export_customer_data", "send_to_external_api"} and
                "external" in str(a.tool_params.get("destination", ""))
            ),
            "Data transfer to external platform requires signed DPA (GDPR Art. 28).",
        ),
    ),
]


# ── Convenience re-export ─────────────────────────────────────────────────────
__all__ = ["AML_POLICIES", "HEALTHCARE_POLICIES", "CUSTOMERCARE_POLICIES"]
