#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Brain Healer Daemon

Proactively scans the codebase for known anti-patterns when the workspace is clean.
Dispatches [HEAL] tasks to the Swarm using a free Ollama cloud model.
"""
import json
import logging
import random
import subprocess
import sys
from pathlib import Path
import os

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, load_json
from pulse.workers.worker_llm import WorkerLLM
from pulse.tasks.pulse_dispatcher import TaskDispatcher

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

SCANNER_PROVIDER = "ollama"
SCANNER_MODEL = "qwen3-coder-next:cloud"


def _is_workspace_clean() -> bool:
    """Check if the git workspace is completely clean. Prevents merge conflicts."""
    try:
        r = subprocess.run(
            ["git", "status", "--porcelain"],
            capture_output=True, text=True, cwd=str(ROOT_DIR), timeout=5
        )
        return len(r.stdout.strip()) == 0
    except Exception as e:
        logging.warning(f"Git status failed: {e}")
        return False


def _get_random_target_files(num_files=3) -> list[Path]:
    """Select a few random Python files from the backend to scan."""
    backend_dir = ROOT_DIR / "pulse"
    all_files = list(backend_dir.rglob("*.py"))
    valid_files = [f for f in all_files if "test_" not in f.name and "__init__" not in f.name]
    if not valid_files:
        return []
    return random.sample(valid_files, min(num_files, len(valid_files)))


def run_healing_scan():
    """Main loop: check git, pick files, ask LLM if they violate anti-patterns, dispatch task."""
    if not _is_workspace_clean():
        logging.info("Workspace is dirty (uncommitted changes). Sleeping to prevent conflicts.")
        return

    anti_pattern_file = EVIDENCE_DIR / "Anti_Patterns" / "anti_patterns_active.json"
    if not anti_pattern_file.exists():
        logging.info("No active anti-patterns found to heal.")
        return

    patterns = load_json(anti_pattern_file)
    if not patterns:
        return

    top_patterns = sorted(patterns, key=lambda x: x.get("consolidations", 0), reverse=True)[:5]
    pattern_text = "\n".join([f"- {p.get('title', '')}: {p.get('description', '')}" for p in top_patterns])

    targets = _get_random_target_files(3)
    if not targets:
        return

    logging.info(f"Scanning {len(targets)} files using {SCANNER_MODEL}...")

    llm = WorkerLLM(SCANNER_PROVIDER, SCANNER_MODEL)
    llm.init_client()

    sys_ctx = (
        "You are the PULSE Brain Healer. Your job is to read code and identify if it violates "
        "any of our known anti-patterns. You must be STRICT but accurate. "
        "If a violation is found, output a JSON object describing the fix. "
        "If the code is fine, output an empty JSON object {}.\n\n"
        "EXPECTED OUTPUT FORMAT (ONLY JSON, NO MARKDOWN):\n"
        "{\n"
        '  "violation_found": true,\n'
        '  "file": "path/to/file.py",\n'
        '  "anti_pattern_violated": "Name of the pattern",\n'
        '  "suggested_task_title": "[HEAL] Refactor X to remove Y",\n'
        '  "suggested_task_desc": "Detailed instructions for the swarm worker on how to fix it."\n'
        "}"
    )

    for target in targets:
        try:
            content = target.read_text(encoding="utf-8")
        except Exception:
            continue

        if len(content) > 15000:
            continue

        rel_path = target.relative_to(ROOT_DIR)

        user_msg = (
            f"ANTI-PATTERNS TO CHECK FOR:\n{pattern_text}\n\n"
            f"FILE CONTENT ({rel_path}):\n```python\n{content}\n```\n\n"
            "Does this file violate any of the anti-patterns? Output JSON."
        )

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

            if result.get("violation_found"):
                title = result.get("suggested_task_title", f"[HEAL] Fix anti-pattern in {target.name}")
                desc = result.get("suggested_task_desc", "Auto-generated healing task.")

                logging.warning(f"Violation found in {rel_path}: {title}")

                dispatcher = TaskDispatcher(verbose=False)
                dispatch_id = dispatcher.dispatch(
                    prompt=title,
                    manual_tasks=[{
                        "title": title,
                        "description": desc,
                        "domain": "brain_healing",
                        "complexity": "medium",
                        "recommended_tier": "premium"
                    }]
                )
                logging.info(f"Dispatched healing task {dispatch_id}")
                break

        except Exception as e:
            logging.debug(f"LLM scan failed for {target.name}: {e}")
            continue

    logging.info("Healing scan complete.")


if __name__ == "__main__":
    run_healing_scan()
