# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
Capture Routing — evidence bucket routing, similarity scoring, domain routing,
growth metrics.

Split from the original combined file for Law 7 compliance.
Batch processing functions (batch_capture, batch_capture_from_log) live in
capture_routing_batch.py and are re-exported here so the single existing
caller (auto_capture.py) keeps working with no import changes.

Dependencies: brain_utils, wants_parser (Python stdlib only via Law 4)
"""

import json
import logging
import re
from datetime import datetime, timezone
from pathlib import Path

from pulse.core.brain_utils import (
    EVIDENCE_DIR, INTENTS_DIR, ANTI_PATTERNS_DIR, STATE_DIR,
    GROWTH_METRICS,
    load_json,
    load_json_dict,
    save_json,
)
from pulse.core.pii_filter import redact_pii

log = logging.getLogger("auto_capture")

# Evidence bucket files (canonical paths — root-level brain regions)
WANTS_EVIDENCE = INTENTS_DIR / "wants.json"
DONT_WANTS_EVIDENCE = INTENTS_DIR / "dont_wants.json"
SESSION_EVIDENCE = EVIDENCE_DIR / "Sessions" / "current_session.json"
ANTI_PATTERNS_ACTIVE = ANTI_PATTERNS_DIR / "anti_patterns_active.json"

# Log line format: [YYYY-MM-DD HH:MM:SS] ROLE: text | SIG: hash
_LOG_LINE_RE = re.compile(
    r"^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (USER|CLAUDE|GEMINI|CODEX|GROK): (.+?)(?:\s*\| SIG: [a-f0-9]+)?$"
)


def is_business_content(text: str) -> bool:
    """Filter non-technical content (pricing, strategy, marketing)."""
    business_signals = [
        "pricing", "revenue", "competitor", "marketing",
        "sales", "invoice", "customer acquisition",
    ]
    text_lower = text.lower()
    return any(signal in text_lower for signal in business_signals)


def count_similar_wants(wants: list, target: str) -> int:
    """Count WANTS similar to target (word overlap > 0.3)."""
    target_words = set(target.lower().split())
    count = 0
    for w in wants:
        w_words = set(w.get("want", "").lower().split())
        if target_words and w_words:
            overlap = len(target_words & w_words) / len(target_words | w_words)
            if overlap > 0.3:
                count += 1
    return count


def count_similar_dont_wants(dont_wants: list, target: str) -> int:
    """Count DON'T_WANTS similar to target."""
    target_words = set(target.lower().split())
    count = 0
    for dw in dont_wants:
        dw_words = set(dw.get("dont_want", "").lower().split())
        if target_words and dw_words:
            overlap = len(target_words & dw_words) / len(target_words | dw_words)
            if overlap > 0.3:
                count += 1
    return count


def route_to_domain(domain: str, prompt: str, response: str,
                    timestamp: str, session_id: str):
    """Route evidence to domain-specific evidence file (SQLite only)."""
    item = {
        "timestamp": timestamp,
        "session_id": session_id,
        "type": "interaction",
        "prompt_summary": redact_pii(prompt[:800]),
        "response_summary": redact_pii(response[:800]) if response else "",
        "domain": domain,
    }
    # P47: SQLite-first write to evidence table
    try:
        from pulse.core.brain_db import insert_knowledge
        insert_knowledge('evidence', {
            'content': (item.get('prompt_summary', '') + ' | ' + item.get('response_summary', ''))[:2000],
            'title': item.get('prompt_summary', '')[:120],
            'domain': domain,
            'agent': item.get('agent', 'bridge'),
            'confidence': 0.5,
            'salience': 1.0,
        })
    except Exception as e:
        log.warning("SQLite evidence write failed: %s", e)


def update_growth_metrics(results: dict):
    """Update growth metrics with capture statistics."""
    metrics = load_json_dict(GROWTH_METRICS)
    cap = metrics.get("auto_capture", {
        "total_captures": 0,
        "total_wants": 0,
        "total_dont_wants": 0,
        "thresholds_hit": 0,
        "synthesis_triggers": 0,
        "last_capture": None,
    })
    cap["total_captures"] = cap.get("total_captures", 0) + 1
    cap["total_wants"] = (
        cap.get("total_wants", 0) + results["wants_stored"]
    )
    cap["total_dont_wants"] = (
        cap.get("total_dont_wants", 0) + results["dont_wants_stored"]
    )
    cap["thresholds_hit"] = (
        cap.get("thresholds_hit", 0) + len(results["thresholds_hit"])
    )
    if results["synthesis_triggered"]:
        cap["synthesis_triggers"] = (
            cap.get("synthesis_triggers", 0) + 1
        )
    cap["last_capture"] = results["timestamp"]
    metrics["auto_capture"] = cap
    save_json(GROWTH_METRICS, metrics)


# ---------------------------------------------------------------------------
# Re-export batch functions so auto_capture.py keeps its existing imports
# without any changes.
# ---------------------------------------------------------------------------
from pulse.brain.capture.capture_routing_batch import (  # noqa: E402, F401
    batch_capture,
    batch_capture_from_log,
)
