import re
import yaml
from typing import Dict, Any, Optional


class SovereignPromptRegistry:
    def __init__(self, langfuse_client):
        self.client = langfuse_client
        # Non-negotiable Dharma: The PAN Redaction Regex
        self.locked_regex = r"[A-Z]{5}[0-9]{4}[A-Z]{1}"

    def _safe_get_prompt(self, name: str) -> Optional[str]:
        """Internal helper to fetch from Langfuse without crashing on 404."""
        try:
            return self.client.get_prompt(name).prompt
        except Exception:
            return None

    def get_mission_prompt(self,
                           task_key: str,
                           user_id: str,
                           agent_id: str,
                           mission_template_id: Optional[str] = None) -> str:
        """
        The 5-Layer Sovereign Merge with specificity prioritization:
        1. Base DNA (Company Root)
        2. User Identity (Persona)
        3. Resolved Task Content (Template > Agent > Core)
        4. Locked Dharma (Hardcoded Guardrail)
        """

        # --- LAYER 1: The Sovereign Foundation ---
        base_dna = self._safe_get_prompt("templates/yantram-ops-dna-v1") or ""

        # --- LAYER 2: The User Identity ---
        # Logic: Extract department from user metadata to find the right persona
        persona_path = f"templates/user-{user_id.lower()}"
        user_persona = self._safe_get_prompt(persona_path)

        if not user_persona:
            # Fallback to general persona based on role substring
            fallback_role = "sdr-sales" if "sdr" in user_id.lower() else "partner-tax"
            user_persona = self._safe_get_prompt(f"templates/user-{fallback_role}-v1") or ""

        # --- LAYER 3: SPECIFICITY RESOLUTION (The Logic Bucket) ---
        # Priority 1: Mission-Specific Override (e.g., templates/mission_bank_audit/reconnaissance)
        task_content = None
        if mission_template_id:
            task_content = self._safe_get_prompt(f"templates/{mission_template_id}/{task_key}")

        # Priority 2: Agent-Specific expertise (e.g., agents/lead_gen/reconnaissance)
        if not task_content:
            task_content = self._safe_get_prompt(f"agents/{agent_id}/{task_key}")

        # Priority 3: Core Default (e.g., core/04_narasimha)
        if not task_content:
            task_content = self._safe_get_prompt(f"core/{task_key}") or f"Execute {task_key} task."

        # --- LAYER 4: THE DEEP MERGE ---
        sovereign_prompt = f"""
{base_dna}

{user_persona}

# MISSION TASK: {task_key.upper()}
{task_content}

# FINAL DHARMA ENFORCEMENT (LOCKED)
- All Indian PAN numbers matching {self.locked_regex} MUST be masked as XXXXX1234X.
- This is a non-negotiable compliance requirement for YantramOps.
- Traceability: All logic payloads must include the session reference.
"""
        return sovereign_prompt

    def verify_enforcement(self, final_output: str) -> bool:
        """
        The Narasimha Post-Process Check.
        Final verification that no raw PAN numbers escaped the masking policy.
        """
        if re.search(self.locked_regex, final_output):
            # In a real scenario, this would trigger an alert in Langfuse
            print("🚨 CRITICAL BREACH: Raw PII (PAN) detected in agent output!")
            return False
        return True