#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Profile Distiller (The "Forgetfulness" Engine)

Reads raw noisy wants and dont_wants, distills them into core engineering principles
using an LLM, updates ~/.pulse/profile.json, and purges the raw noise.
"""
import json
import logging
import os
import sys
from pathlib import Path
from datetime import datetime, timezone

if os.name == "nt":
    sys.stdout.reconfigure(encoding="utf-8")
    sys.stderr.reconfigure(encoding="utf-8")

ROOT_DIR = Path(__file__).resolve().parents[2]
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from pulse.core.brain_utils import EVIDENCE_DIR, STATE_DIR, load_json, save_json
from pulse.workers.worker_llm import WorkerLLM

logging.basicConfig(level=logging.INFO, format="%(asctime)s [DISTILLER] %(levelname)s %(message)s", datefmt="%H:%M:%S")

DISTILLER_PROVIDER = "ollama"
DISTILLER_MODEL = "qwen3-coder-next:cloud"
PROFILE_FILE = STATE_DIR / "user_profile.json"
WANTS_FILE = EVIDENCE_DIR / "Intents" / "wants.json"
DONT_WANTS_FILE = EVIDENCE_DIR / "Intents" / "dont_wants.json"
ARCHIVE_DIR = EVIDENCE_DIR / "Intents" / "Archive"


def _archive_and_purge(wants: list, dont_wants: list):
    """Save the raw noise to the archive before deleting it."""
    ARCHIVE_DIR.mkdir(parents=True, exist_ok=True)
    ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")

    if wants:
        save_json(ARCHIVE_DIR / f"wants_archived_{ts}.json", wants)
        save_json(WANTS_FILE, [])

    if dont_wants:
        save_json(ARCHIVE_DIR / f"dont_wants_archived_{ts}.json", dont_wants)
        save_json(DONT_WANTS_FILE, [])


def run_distillation():
    wants = load_json(WANTS_FILE)
    dont_wants = load_json(DONT_WANTS_FILE)

    total_items = len(wants) + len(dont_wants)
    if total_items < 15:
        logging.info(f"Only {total_items} intent items. Waiting for >=15 to distill.")
        return

    logging.info(f"Distilling {len(wants)} wants and {len(dont_wants)} dont_wants into the User Profile...")

    current_profile = {}
    if PROFILE_FILE.exists():
        current_profile = load_json(PROFILE_FILE)
        if isinstance(current_profile, list):
            current_profile = current_profile[0] if current_profile else {}

    wants_text = "\n".join([f"- {w.get('want', w.get('description', str(w)))}" for w in wants])
    dont_wants_text = "\n".join([f"- {dw.get('dont_want', dw.get('description', str(dw)))}" for dw in dont_wants])

    current_profile_str = json.dumps(current_profile, indent=2) if current_profile else "{}"

    llm = WorkerLLM(DISTILLER_PROVIDER, DISTILLER_MODEL)
    llm.init_client()

    sys_ctx = (
        "You are the PULSE Cognitive Distiller. Your job is to read raw user requests (wants/dont_wants) "
        "and compress them into a highly-condensed 'User Profile'.\n"
        "Eliminate contradictions, remove noise, and extract the underlying *Principles*.\n"
        "Output ONLY a JSON object merging the new insights with the current profile.\n\n"
        "EXPECTED JSON SCHEMA:\n"
        "{\n"
        '  "engineering_principles": ["Principle 1", "Principle 2"],\n'
        '  "formatting_preferences": ["Formatting 1"],\n'
        '  "workflow_habits": ["Habit 1"],\n'
        '  "strict_prohibitions": ["Never do X"]\n'
        "}"
    )

    user_msg = (
        f"CURRENT PROFILE:\n```json\n{current_profile_str}\n```\n\n"
        f"NEW WANTS (Integrate these):\n{wants_text}\n\n"
        f"NEW DONT_WANTS (Integrate these):\n{dont_wants_text}\n\n"
        "Please distill all this into a single, updated JSON Profile."
    )

    try:
        text, _, _ = llm.call_llm(sys_ctx, [{"role": "user", "content": user_msg}])
        text = text.replace("```json", "").replace("```", "").strip()
        new_profile = json.loads(text)

        if not new_profile.get("engineering_principles") and not new_profile.get("strict_prohibitions"):
            raise ValueError("Distilled profile is empty or invalid.")

        save_json(PROFILE_FILE, new_profile)
        logging.info("Successfully distilled user profile!")

        _archive_and_purge(wants, dont_wants)
        logging.info("Archived and purged raw intents.")

    except Exception as e:
        logging.error(f"Distillation failed: {e}")


if __name__ == "__main__":
    run_distillation()
