#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
Auto-Capture Daemon: Real-time evidence capture from terminal interactions (V43.14)

Core capture loop and thresholds. CLI logic moved to auto_capture_cli.py for SoC.
"""

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

SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent.parent
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from pulse.core.brain_utils import (
    EVIDENCE_DIR, load_config, load_json, save_json,
)
from pulse.brain.extraction.wants_parser import parse_full
from pulse.core.pii_filter import redact_pii

from pulse.brain.capture.capture_routing import (
    WANTS_EVIDENCE, DONT_WANTS_EVIDENCE, SESSION_EVIDENCE,
    is_business_content as _is_business_content,
    count_similar_wants as _count_similar_wants,
    count_similar_dont_wants as _count_similar_dont_wants,
    route_to_domain as _route_to_domain,
    update_growth_metrics as _update_growth_metrics,
    batch_capture as _batch_capture_impl,
    batch_capture_from_log as _batch_capture_from_log_impl,
)

log = logging.getLogger("auto_capture")


def capture(user_prompt: str, agent_response: str = "",
            session_id: str = "") -> dict:
    """Main capture function: parse input and route to evidence buckets."""
    if not user_prompt or len(user_prompt.strip()) < 3:
        return {"status": "skipped", "reason": "prompt too short"}

    if _is_business_content(user_prompt):
        return {"status": "skipped", "reason": "business content filtered"}

    now = datetime.now(timezone.utc).isoformat()
    config = load_config()
    parsed = parse_full(user_prompt, agent_response)

    results = {
        "timestamp": now, "wants_stored": 0, "dont_wants_stored": 0,
        "session_items": 0, "thresholds_hit": [], "synthesis_triggered": False,
    }

    # 1. Store WANTS
    if parsed["wants"]:
        for want in parsed["wants"]: want["session_id"] = session_id
        wants_sqlite_ok = False
        try:
            from pulse.core.brain_db import insert_knowledge as _ins_k
            _sqlite_written = 0
            for want in parsed["wants"]:
                content = (want.get("want") or "").strip()
                if len(content) >= 15:
                    _ins_k("intents", {
                        "content": content, "type": "want", "domain": want.get("domain", "general"),
                        "agent": want.get("_agent_id") or "auto_capture", "timestamp": now,
                        "salience": float(want.get("salience") or 1.0),
                        "confidence": float(want.get("confidence") or 0.6),
                        "metadata": {"session_id": session_id, "source": "auto_capture"},
                    })
                    _sqlite_written += 1
            wants_sqlite_ok = _sqlite_written > 0
        except Exception: pass

        if not wants_sqlite_ok:
            wants = load_json(WANTS_EVIDENCE)
            wants.extend(parsed["wants"])
            save_json(WANTS_EVIDENCE, wants)
        else:
            try:
                from pulse.core.brain_db import get_conn
                rows = get_conn().execute("SELECT content as want FROM intents WHERE type='want' LIMIT 500").fetchall()
                wants = [dict(r) for r in rows]
            except Exception: wants = parsed["wants"]

        results["wants_stored"] = len(parsed["wants"])
        if parsed["wants"] and _count_similar_wants(wants, parsed["wants"][-1]["want"]) >= 3:
            results["thresholds_hit"].append("wants_benchmark")

    # 2. Store DON'T_WANTS
    if parsed["dont_wants"]:
        for dw in parsed["dont_wants"]:
            dw["session_id"] = session_id
            dw["status"] = "active"
        dw_sqlite_ok = False
        try:
            from pulse.core.brain_db import insert_knowledge as _ins_k
            _dw_written = 0
            for dw in parsed["dont_wants"]:
                content = (dw.get("dont_want") or "").strip()
                if len(content) >= 15:
                    _ins_k("intents", {
                        "content": content, "type": "dont_want", "domain": dw.get("domain", "general"),
                        "agent": dw.get("_agent_id") or "auto_capture", "timestamp": now,
                        "salience": float(dw.get("salience") or 1.0),
                        "confidence": float(dw.get("confidence") or 0.6),
                        "metadata": {"session_id": session_id, "reason": dw.get("reason", ""), "source": "auto_capture"},
                    })
                    _dw_written += 1
            dw_sqlite_ok = _dw_written > 0
        except Exception: pass

        if not dw_sqlite_ok:
            dont_wants = load_json(DONT_WANTS_EVIDENCE)
            dont_wants.extend(parsed["dont_wants"])
            save_json(DONT_WANTS_EVIDENCE, dont_wants)
        else:
            try:
                from pulse.core.brain_db import get_conn
                rows = get_conn().execute("SELECT content as dont_want FROM intents WHERE type='dont_want' LIMIT 500").fetchall()
                dont_wants = [dict(r) for r in rows]
            except Exception: dont_wants = parsed["dont_wants"]

        results["dont_wants_stored"] = len(parsed["dont_wants"])
        if parsed["dont_wants"] and _count_similar_dont_wants(dont_wants, parsed["dont_wants"][-1].get("dont_want", "")) >= 2:
            results["thresholds_hit"].append("anti_pattern_build")
            try:
                from pulse.core.user_profile import UserProfile
                profile = UserProfile.load()
                for dw in parsed["dont_wants"]:
                    text = dw.get("dont_want", "")[:100]
                    if text and text not in profile.dont_wants: profile.dont_wants.append(text)
                profile.dont_wants = profile.dont_wants[-20:]
                profile.save()
            except Exception: pass

    # 3. Store session evidence in SQLite (JSON deprecated)
    description = redact_pii((user_prompt[:200] or agent_response[:200] or "[no content]").strip())
    session_item = {
        "type": "OBSERVATION", "source": "auto_capture", "timestamp": now, "session_id": session_id,
        "domain": parsed["primary_domain"], "priority": parsed["priority"], "description": description,
        "has_wants": len(parsed["wants"]) > 0, "has_dont_wants": len(parsed["dont_wants"]) > 0,
        "has_rejection": parsed["has_rejection"], "prompt_length": len(user_prompt), "response_length": len(agent_response),
    }

    try:
        from pulse.core.brain_db import insert_knowledge as _ins_k
        _ins_k("evidence", {
            "content": description, "type": "OBSERVATION", "domain": parsed["primary_domain"],
            "agent": "auto_capture", "timestamp": now,
            "salience": 1.0, "confidence": 0.8,
            "metadata": session_item
        })
    except Exception as e:
        log.warning("SQLite session evidence write failed: %s", e)
        session_data = load_json(SESSION_EVIDENCE)
        session_data.append(session_item)
        save_json(SESSION_EVIDENCE, session_data)

    results["session_items"] = 1

    try:
        from pulse.brain.index.episodic_writer import save_episode
        save_episode(agent="capture_daemon", domain=parsed["primary_domain"],
                     session_summary=f"Capture: {description[:200]}",
                     key_events=[w.get("want", "")[:80] for w in parsed["wants"][:3]],
                     session_id=session_id)
    except Exception: pass

    domain = parsed["primary_domain"]
    if domain != "general": _route_to_domain(domain, user_prompt, agent_response, now, session_id)

    # Synthesis threshold check (SQLite authoritative)
    try:
        from pulse.core.brain_db import get_conn
        _count_sql = get_conn().execute(
            "SELECT COUNT(*) FROM evidence WHERE domain=? AND (type='LEARNING' OR type='OBSERVATION')", (domain,)
        ).fetchone()[0]
        if _count_sql >= config.get("synthesis", {}).get("domain_thresholds", {}).get(domain, config.get("synthesis", {}).get("default_threshold", 5)):
            results["synthesis_triggered"] = True
    except Exception:
        domain_evidence_file = EVIDENCE_DIR / "Learnings" / f"{domain}_learnings.json"
        if domain_evidence_file.exists():
            if len(load_json(domain_evidence_file)) >= config.get("synthesis", {}).get("domain_thresholds", {}).get(domain, config.get("synthesis", {}).get("default_threshold", 5)):
                results["synthesis_triggered"] = True

    _update_growth_metrics(results)
    return results

def batch_capture() -> dict: return _batch_capture_impl(capture)
def batch_capture_from_log(log_path: str) -> dict: return _batch_capture_from_log_impl(log_path, capture)

if __name__ == "__main__":
    # Backward compat entry point - now routes to CLI wrapper logic if needed,
    # but primarily serves as a logic container.
    pass
