#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Stages 4b/3c: Promote high-confidence items to patterns."""
import hashlib
import re

from pulse.core.brain_utils import (
    LESSONS_DIR, FAILS_DIR, PATTERNS_DIR,
    now_iso as _now_iso,
)
from .stage_io import _get_entries_for_file

_PRESCRIPTIVE = re.compile(
    r"\b(?:always|never|must|should|avoid|ensure|require|prevent|"
    r"don't|do not|critical|important)\b", re.IGNORECASE
)


def stage_promote_to_patterns(verbose=False):
    """Promote high-confidence lessons/failures (conf >= 0.7, prescriptive) to patterns."""
    from pulse.core.brain_db import insert_knowledge
    promoted = 0
    promoted_items = []

    for md_file in [LESSONS_DIR / "auto_lessons.md", FAILS_DIR / "auto_fails.md"]:
        for e in _get_entries_for_file(md_file):
            title = e["title"]
            if e["conf"] < 0.7 or not _PRESCRIPTIVE.search(title):
                continue
            ts = e.get("date", "") or _now_iso()[:10]
            source = e.get("source", "consolidation")
            fp = hashlib.md5(title[:80].lower().strip().encode("utf-8")).hexdigest()[:12]
            entry = {
                "fingerprint": fp,
                "type": "pattern",
                "content": title,
                "title": title,
                "domain": e.get("domain", "general"),
                "agent": source,
                "timestamp": ts,
                "confidence": e["conf"],
                "salience": e.get("salience", 2.0),
                "validity": "valid",
                "provenance": {"stage": "promotion", "from_file": md_file.name, "agent": source},
            }
            insert_knowledge("patterns", entry)
            promoted_items.append(entry)
            promoted += 1
            try:
                from pulse.brain.integrity.provenance import append_provenance
                append_provenance(fp, {
                    "stage": "promotion",
                    "from_file": md_file.name,
                    "to_file": "patterns (SQLite)",
                    "agent": source,
                })
            except Exception:
                pass

    if verbose:
        print(f"  [PROMOTE] {promoted} high-confidence items promoted to patterns")

    # Stage 4c: Promote repeated failures (3+ occurrences) to anti-patterns.
    # Dead code wired here so the no-repeat-mistakes enforcement actually runs
    # every consolidation cycle.
    try:
        from pulse.admin.patterns.anti_pattern_builder import promote_repeated_failures
        promote_repeated_failures()
    except Exception:
        pass

    return {"status": "ok", "promoted": promoted_items}


def stage_3c_micro_pattern_promotion(verbose=False):
    """Stage 3c: Promote lessons with consolidation_count >= 3 to patterns."""
    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        res = conn.execute("""
            SELECT * FROM lessons
            WHERE consolidation_count >= 3 AND validity = 'valid'
        """)
        promotable = res.fetchall()
        promoted = 0
        with conn:
            for row in promotable:
                conn.execute("""
                    INSERT OR IGNORE INTO patterns
                    (id, fingerprint, type, content, title, domain, agent, timestamp, salience, confidence, validity)
                    VALUES (?, ?, 'pattern', ?, ?, ?, ?, ?, ?, ?, ?)
                """, (row["id"].replace("L-", "P-"), row["fingerprint"], row["content"],
                      row["title"], row["domain"], "daemon", row["timestamp"], row["salience"],
                      row["confidence"] if row["confidence"] else 0.7,
                      row["validity"] if row["validity"] else "valid"))
                promoted += 1
        if verbose:
            print(f"  [3C] Promoted {promoted} micro-patterns.")
        return {"promoted_patterns": promoted}
    except ImportError:
        if verbose:
            print("  [3C] SQLite DAL not fully loaded")
        return {"status": "skipped"}
    except Exception as e:
        if verbose:
            print(f"  [3C] Error: {e}")
        return {"error": str(e)}
