#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Consolidation Promotion: Schema promotion from cross-session patterns
and event sequences.

Split from consolidation_mining.py for Law 7 compliance.
"""

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

from pulse.core.brain_utils import PATTERNS_DIR, load_json_dict, save_json, now_iso as _now_iso


def promote_cross_patterns_to_schemas(cross_patterns, verbose=False):
    """Promote high-confidence cross-session patterns to schemas.json."""
    SCHEMAS_FILE = PATTERNS_DIR / "schemas.json"
    schemas_data = load_json_dict(SCHEMAS_FILE)
    if "schemas" not in schemas_data:
        schemas_data["schemas"] = []

    existing_names = {s.get("name", "").lower() for s in schemas_data["schemas"]}
    new_count = 0

    for pattern in cross_patterns:
        confidence = pattern.get("max_confidence", 0)
        consolidations = pattern.get("total_consolidations", 0)
        unique_dates = pattern.get("unique_dates", 0)

        if confidence < 0.5:
            continue
        if consolidations < 3 and unique_dates < 2:
            continue

        name = pattern["title"][:60]
        if name.lower() in existing_names:
            for s in schemas_data["schemas"]:
                if s.get("name", "").lower() == name.lower():
                    s["evidence_count"] = max(s.get("evidence_count", 0), pattern.get("occurrences", 1))
                    s["confidence"] = max(s.get("confidence", 0), confidence)
                    s["last_reinforced"] = _now_iso()
                    break
            continue

        schema_id = f"S-{len(schemas_data['schemas']) + 1:03d}"
        schemas_data["schemas"].append({
            "schema_id": schema_id,
            "name": name,
            "description": pattern["title"],
            "evidence_count": pattern.get("occurrences", 1),
            "confidence": round(confidence, 3),
            "created": _now_iso(),
            "source": pattern.get("source", "consolidation"),
            "unique_dates": unique_dates,
            "total_consolidations": consolidations,
        })
        existing_names.add(name.lower())
        new_count += 1
        if verbose:
            print(f"  [SCHEMA] Promoted: {name} (conf={confidence:.2f})")

    if new_count > 0 or any(p.get("max_confidence", 0) >= 0.7 for p in cross_patterns):
        schemas_data["last_updated"] = _now_iso()
        save_json(SCHEMAS_FILE, schemas_data)

    if verbose:
        print(f"  [SCHEMA] {new_count} new schemas, {len(schemas_data['schemas'])} total")

    return {"status": "ok", "new_schemas": new_count, "total_schemas": len(schemas_data["schemas"])}


def promote_sequences_to_schemas(sequences, verbose=False):
    """Promote event sequences with 5+ occurrences to schemas.json."""
    SCHEMAS_FILE = PATTERNS_DIR / "schemas.json"
    schemas_data = load_json_dict(SCHEMAS_FILE)
    if "schemas" not in schemas_data:
        schemas_data["schemas"] = []

    existing_names = {s.get("name", "").lower() for s in schemas_data["schemas"]}
    new_count = 0

    for seq in sequences:
        count = seq.get("count", 0)
        if count < 5:
            continue
        confidence = seq.get("confidence", 0.5)
        name = f"Sequence: {seq['sequence'][:50]}"

        if name.lower() in existing_names:
            for s in schemas_data["schemas"]:
                if s.get("name", "").lower() == name.lower():
                    s["evidence_count"] = max(s.get("evidence_count", 0), count)
                    s["confidence"] = max(s.get("confidence", 0), confidence)
                    s["last_reinforced"] = _now_iso()
                    break
            continue

        schema_id = f"S-{len(schemas_data['schemas']) + 1:03d}"
        schemas_data["schemas"].append({
            "schema_id": schema_id,
            "name": name,
            "description": f"Recurring event sequence: {seq['sequence']}",
            "evidence_count": count,
            "confidence": round(confidence, 3),
            "created": _now_iso(),
            "source": "sequence_mining",
            "type": "procedural",
        })
        existing_names.add(name.lower())
        new_count += 1
        if verbose:
            print(f"  [SCHEMA] Promoted sequence: {name} (count={count})")

    if new_count > 0:
        schemas_data["last_updated"] = _now_iso()
        save_json(SCHEMAS_FILE, schemas_data)

    if verbose:
        print(f"  [SCHEMA] {new_count} sequences promoted to schemas")

    return {"new_from_sequences": new_count}
