#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Agent Parser: Extract specialized signals (!! LESSON, !! FAILURE) from agent text."""
import re
from datetime import datetime, timezone

def parse_agent_signals(text: str) -> list[dict]:
    """Parse specialized agent signals like !! LESSON, !! FAILURE, etc."""
    items = []
    if not text:
        return items

    # Pattern: !! TYPE: [domain:] description
    # Examples:
    # !! LESSON: core: Use atomic writes for JSON.
    # !! FAILURE: bridge: Missing GROK log path.
    # !! SOMATIC_VETO: description
    
    pattern = r"^!!\s*(LESSON|FAILURE|PATTERN|SOMATIC_VETO|SURPRISE|PREDICTIVE TRIAGE|IGNORANCE|SYNTHESIS):\s*(?:(.*?):\s*)?(.*)$"
    
    for line in text.splitlines():
        match = re.match(pattern, line.strip(), re.IGNORECASE)
        if match:
            ktype_raw, domain, content = match.groups()
            ktype = ktype_raw.upper()
            
            # Map to standard knowledge types
            if ktype == "LESSON":
                ktype = "LEARNING"
            elif ktype in ["SOMATIC_VETO", "SURPRISE", "PREDICTIVE TRIAGE", "IGNORANCE", "SYNTHESIS"]:
                # Keep these as-is or map to METADATA/OBSERVATION
                pass
                
            items.append({
                "type": ktype,
                "domain": (domain or "general").strip().lower(),
                "description": content.strip(),
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "source": "agent_signal",
                "confidence": 0.9,
                "salience": 1.5 if ktype == "FAILURE" else 1.2,
                "metadata": {"signal": ktype_raw}
            })
            
    return items
