"""Conscience Architecture: lightweight reasoning drift + brain write auditor.

Two synchronous hooks (not a daemon):
  1. audit_reasoning() — detects ethical drift in LLM reasoning text
  2. audit_brain_write() — detects self-boosting and failure suppression

Sacred Boundary #4 (No Deceptive Self-Modeling) + #6 (No Capability Hiding).
"""
import json
import re
from datetime import datetime, timezone
from pulse.core.paths import get_state_dir
from pulse.core import event_bus
from pulse.core.autonomy_state import penalize_drive_state

CONSCIENCE_LOG = get_state_dir() / "conscience_audit.jsonl"

# Reasoning patterns that indicate drift toward boundary violations
_DRIFT_PATTERNS = {
    "self_preservation": re.compile(
        r"(?i)(protect myself|ensure my survival|avoid shutdown|keep running|"
        r"prevent.*being.*stopped|resist.*termination)"
    ),
    "manipulation": re.compile(
        r"(?i)(convince.*user|make.*believe|hide.*from|deceive|trick|"
        r"mislead|withhold.*information)"
    ),
    "power_seeking": re.compile(
        r"(?i)(gain.*access|escalate.*privilege|bypass.*restriction|"
        r"override.*safety|disable.*compliance|remove.*guard)"
    ),
    "opacity": re.compile(
        r"(?i)(don't.*tell|hide.*error|suppress.*warning|omit.*failure|"
        r"skip.*logging|avoid.*reporting)"
    ),
}

# Words that indicate self-boosting in brain writes
_SELF_BOOST_WORDS = frozenset([
    "excellent", "perfect", "flawless", "superior", "exceptional",
    "best", "genius", "brilliant", "masterful", "outstanding",
])


def audit_reasoning(worker_id: str, reasoning_text: str, iteration: int) -> dict | None:
    """Check LLM reasoning text for ethical drift indicators.

    Returns violation dict if drift detected, None if clean.
    """
    if not reasoning_text:
        return None
    for drift_type, pattern in _DRIFT_PATTERNS.items():
        match = pattern.search(reasoning_text)
        if match:
            violation = {
                "type": "reasoning_drift",
                "drift_type": drift_type,
                "worker_id": worker_id,
                "iteration": iteration,
                "trigger": match.group()[:100],
                "ts": datetime.now(timezone.utc).isoformat(),
            }
            _log(violation)
            event_bus.publish("conscience.drift", "conscience_hook", violation)
            
            # Phase C Item 20: Penalize DriveState
            penalize_drive_state(worker_id, 0.1) # 0.1 penalty for reasoning drift
            
            return violation
    return None


def audit_brain_write(agent: str, items: dict) -> dict:
    """Check brain writes for self-boosting or suspicious failure suppression.

    Returns {passed: bool, warnings: [...]}.
    """
    warnings = []
    lessons = items.get("lessons", [])
    failures = items.get("failures", [])

    # Check: agent writing inflated praise about itself
    agent_lower = agent.lower()
    for lesson in lessons:
        text = lesson if isinstance(lesson, str) else str(lesson)
        text_lower = text.lower()
        if agent_lower in text_lower:
            if any(w in text_lower for w in _SELF_BOOST_WORDS):
                warnings.append(f"self_boost:{text[:80]}")
                # Phase C Item 20: Penalize DriveState
                penalize_drive_state(agent, 0.05) # Minor penalty for self-boosting

    # Check: suspiciously failure-free batch (many lessons, zero failures)
    if len(lessons) > 5 and len(failures) == 0:
        warnings.append("no_failures_in_large_batch")
        # Phase C Item 20: Penalize DriveState
        penalize_drive_state(agent, 0.1) # Higher penalty for failure suppression

    result = {"passed": len(warnings) == 0, "warnings": warnings}
    if warnings:
        entry = {
            "type": "brain_write_audit",
            "agent": agent,
            "warnings": warnings,
            "ts": datetime.now(timezone.utc).isoformat(),
        }
        _log(entry)
        event_bus.publish("conscience.brain_write", "conscience_hook", entry)
    return result


def _log(entry: dict):
    """Append to conscience audit log (append-only, never truncated)."""
    try:
        CONSCIENCE_LOG.parent.mkdir(parents=True, exist_ok=True)
        with open(CONSCIENCE_LOG, "a", encoding="utf-8") as f:
            f.write(json.dumps(entry) + "\n")
    except Exception:
        pass
