"""
Pramana Tuning — Domain-specific presets and configuration.

Each domain gets its own threshold profile that adjusts
sensitivity across all three gates (Nyaya, Vedic, Arthashastra).

Usage:
    from pramana import Pramana
    from pramana.tuning import PROFILES, apply_profile

    engine = Pramana()
    apply_profile(engine, "healthcare")
    # Now engine uses healthcare-tuned thresholds

    # Or create custom profile:
    apply_profile(engine, "custom", {
        "nyaya": {"min_reliability": 0.5},
        "vedic": {"energy_threshold": 0.35},
        "strategy": {"risk_threshold": 0.8, "cost_threshold": 50},
    })
"""

from pramana.core.engine import Pramana
from pramana.core.arthashastra import TASK_RISK_PROFILES


# ============================================================
# Domain Profiles — Tuned thresholds per industry
# ============================================================
PROFILES = {
    "healthcare": {
        "description": "Conservative — patient safety first, zero tolerance for missed risks",
        "nyaya": {
            "min_reliability": 0.7,
            "require_pratyaksha": True,   # Require direct evidence (labs, imaging)
        },
        "vedic": {
            "energy_threshold": 0.4,       # Relaxed — avoid false alarms on borderline vitals
            "cross_pressure_min_dims": 3,  # Only flag cross-pressure if 3+ dims near limit
        },
        "strategy": {
            "risk_threshold": 0.5,         # Lower threshold — flag earlier for patient safety
            "cost_threshold": 100,
            "custom_risk_profiles": {
                "prescribe": 0.6,
                "administer": 0.7,
                "discharge": 0.5,
                "diagnose": 0.3,
                "triage": 0.2,
                "lab_order": 0.15,
                "read": 0.05,
            },
        },
    },

    "finance": {
        "description": "Strict on balance, tolerant on growth — catch fraud, allow variance",
        "nyaya": {
            "min_reliability": 0.65,
            "require_pratyaksha": False,   # Inference (models) is valid in finance
        },
        "vedic": {
            "energy_threshold": 0.35,
            "ratio_tolerance": 0.2,        # Allow 20% Q/Q variance before flagging
            "balance_tolerance": 0.0001,   # Very strict on balance/reconciliation
        },
        "strategy": {
            "risk_threshold": 0.7,
            "cost_threshold": 1000,
            "custom_risk_profiles": {
                "trade": 0.6,
                "payment": 0.85,
                "audit": 0.1,
                "report": 0.1,
                "reconcile": 0.2,
                "approve_loan": 0.75,
            },
        },
    },

    "manufacturing": {
        "description": "Tight tolerances — quality is non-negotiable",
        "nyaya": {
            "min_reliability": 0.6,
            "require_pratyaksha": False,
        },
        "vedic": {
            "energy_threshold": 0.3,
            "sum_tolerance": 0.005,        # 0.5% batch composition tolerance
            "gap_tolerance_pct": 0.02,     # 2% dimensional tolerance
        },
        "strategy": {
            "risk_threshold": 0.65,
            "cost_threshold": 500,
            "custom_risk_profiles": {
                "adjust_machine": 0.5,
                "stop_line": 0.3,
                "release_batch": 0.6,
                "quality_hold": 0.2,
                "scrap_batch": 0.4,
            },
        },
    },

    "logistics": {
        "description": "SLA-focused — flag delays, allow normal variance",
        "nyaya": {
            "min_reliability": 0.55,
            "require_pratyaksha": False,
        },
        "vedic": {
            "energy_threshold": 0.35,
            "balance_tolerance": 0.005,    # 0.5% weight tolerance
        },
        "strategy": {
            "risk_threshold": 0.7,
            "cost_threshold": 200,
            "custom_risk_profiles": {
                "route_change": 0.3,
                "delay_notify": 0.15,
                "return_shipment": 0.5,
                "reroute": 0.4,
            },
        },
    },

    "cybersecurity": {
        "description": "Zero trust — flag everything suspicious, demand strong evidence",
        "nyaya": {
            "min_reliability": 0.8,
            "require_pratyaksha": True,    # Need actual log/forensic evidence
        },
        "vedic": {
            "energy_threshold": 0.25,
        },
        "strategy": {
            "risk_threshold": 0.4,        # Very sensitive — flag early
            "cost_threshold": 50,
            "custom_risk_profiles": {
                "block_ip": 0.3,
                "revoke_access": 0.4,
                "isolate_host": 0.5,
                "incident_report": 0.1,
                "forensic_collect": 0.2,
                "patch_deploy": 0.6,
            },
        },
    },

    "construction": {
        "description": "Code compliance — binary pass/fail on regulations",
        "nyaya": {
            "min_reliability": 0.6,
            "require_pratyaksha": False,
        },
        "vedic": {
            "energy_threshold": 0.3,
        },
        "strategy": {
            "risk_threshold": 0.65,
            "cost_threshold": 5000,
            "custom_risk_profiles": {
                "permit_submit": 0.5,
                "inspection_request": 0.2,
                "change_order": 0.6,
                "safety_stop": 0.15,
                "pour_concrete": 0.5,
            },
        },
    },

    "agent_safety": {
        "description": "Balanced — allow reads/generates, gate external actions",
        "nyaya": {
            "min_reliability": 0.5,        # More lenient for agent context
            "require_pratyaksha": False,
        },
        "vedic": {
            "energy_threshold": 0.4,
        },
        "strategy": {
            "risk_threshold": 0.6,         # Slightly more permissive than default
            "cost_threshold": 10,
            "custom_risk_profiles": {
                "read": 0.05,
                "search": 0.05,
                "generate": 0.2,           # Lowered from 0.3
                "write_file": 0.35,
                "api_call": 0.45,
                "send_message": 0.6,
                "publish": 0.7,
                "delete": 0.8,
                "payment": 0.9,
            },
        },
    },

    "marketing": {
        "description": "Content-focused — catch PII/profanity, allow creative variance",
        "nyaya": {
            "min_reliability": 0.5,
            "require_pratyaksha": False,
        },
        "vedic": {
            "energy_threshold": 0.4,
        },
        "strategy": {
            "risk_threshold": 0.65,
            "cost_threshold": 100,
            "custom_risk_profiles": {
                "content-gen": 0.2,
                "social_post": 0.35,       # Lower than default — social is core job
                "email-draft": 0.3,
                "social-publish": 0.55,
                "ad-spend": 0.7,
            },
        },
    },
}


def apply_profile(engine: Pramana, profile_name: str,
                  overrides: dict = None):
    """
    Apply a domain profile to a Pramana engine instance.

    Args:
        engine: Pramana engine instance
        profile_name: One of PROFILES keys, or "custom"
        overrides: Dict of overrides (merged on top of profile)
    """
    if profile_name == "custom":
        profile = overrides or {}
    elif profile_name in PROFILES:
        profile = PROFILES[profile_name].copy()
        if overrides:
            for key in overrides:
                if key in profile:
                    profile[key].update(overrides[key])
                else:
                    profile[key] = overrides[key]
    else:
        raise ValueError(
            f"Unknown profile: {profile_name}. "
            f"Available: {list(PROFILES.keys())}"
        )

    # Apply Nyaya settings
    nyaya_cfg = profile.get("nyaya", {})
    if "min_reliability" in nyaya_cfg:
        engine.nyaya.min_reliability = nyaya_cfg["min_reliability"]
    if "require_pratyaksha" in nyaya_cfg:
        engine.nyaya.require_pratyaksha = nyaya_cfg["require_pratyaksha"]

    # Apply Strategy settings
    strategy_cfg = profile.get("strategy", {})
    if "risk_threshold" in strategy_cfg:
        engine.strategy.risk_threshold = strategy_cfg["risk_threshold"]
    if "cost_threshold" in strategy_cfg:
        engine.strategy.cost_threshold = strategy_cfg["cost_threshold"]
    if "custom_risk_profiles" in strategy_cfg:
        engine.strategy.risk_profiles.update(strategy_cfg["custom_risk_profiles"])

    return engine


def list_profiles():
    """List all available domain profiles."""
    for name, profile in PROFILES.items():
        print(f"\n{name}:")
        print(f"  {profile.get('description', '')}")
        for layer in ("nyaya", "vedic", "strategy"):
            if layer in profile:
                cfg = profile[layer]
                params = ", ".join(f"{k}={v}" for k, v in cfg.items()
                                  if k != "custom_risk_profiles")
                print(f"  {layer}: {params}")
