#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Wrapper Skills: Skill loading and domain mapping for PULSE agents.

Extracted from pulse_wrapper.py per Law 7 (files <= 300 lines).

Functions:
  - load_skills_for_domain(): Auto-inject domain-specific skills
  - load_skills_interactive(): Universal skills + index for interactive sessions
"""
from __future__ import annotations

import sys
from pathlib import Path

from pulse.core.brain_utils import SKILLS_DIR  # noqa: E402

# Domain keywords -> skill files to auto-inject.
_DOMAIN_SKILL_MAP = {
    # Core domains
    "security":      ["Security/SECURITY_VANGUARD", "Security/ZERO_TRUST", "Security/AUDITOR"],
    "architecture":  ["Architecture/ARCHITECT", "Architecture/MASTER_ARCHITECT", "Architecture/SYSTEM_HARMONIZER"],
    "testing":       ["Development/TEST_STRATEGIST", "Development/TEST_DRIVEN", "General/DEBUG_WARLORD"],
    "system":        ["Development/CODE_VANGUARD", "Development/REFACTOR_DRUID", "General/SHELL_SORCERER"],
    "features":      ["Development/CODE_VANGUARD", "Development/API_GURU"],
    "refactoring":   ["Development/REFACTOR_DRUID", "Architecture/COMPLEXITY_CRUSHER"],
    "docs":          ["General/DOCU_FORGE", "General/DOC_QUALITY", "General/TOKEN_VAULT"],
    "devops":        ["Development/CI_CD_COMMANDER", "Development/DOCKER_DRILL"],
    "database":      ["Architecture/DATABASE_WHISPERER", "Development/API_GURU"],
    "git":           ["GIT_PRACTICES/COMMIT_ALCHEMIST", "GIT_PRACTICES/GIT_SENTINEL"],
    "orchestration": ["Orchestration/ORCHESTRATOR", "Orchestration/BRAIN_NAVIGATOR", "Orchestration/SKILL_NAVIGATOR"],
    "brain":         ["Orchestration/BRAIN_NAVIGATOR", "Orchestration/MEMORY_MINER"],
    "performance":   ["General/SPEED_V2", "General/LATENCY_LAYER"],
    "api":           ["Development/API_GURU", "Architecture/NETWORK_NOMAD"],
    "ui":            ["Architecture/UI_ALCHEMIST", "Architecture/UX_PSYCHOLOGIST"],
    # Extended domains
    "debugging":     ["General/DEBUG_WARLORD", "Development/ERROR_RECOVERY"],
    "ml":            ["General/AI_NEUROLOGIST", "General/DATA_DYNAMO"],
    "data":          ["General/DATA_DYNAMO", "Architecture/DATABASE_WHISPERER"],
    "frontend":      ["Architecture/UI_ALCHEMIST", "Architecture/UX_PSYCHOLOGIST"],
    "backend":       ["Development/API_GURU", "Architecture/DATABASE_WHISPERER"],
    "cloud":         ["General/CLOUD_CATALYST", "Development/DOCKER_DRILL"],
    "documentation": ["General/DOCU_FORGE", "General/DOC_QUALITY"],
    "optimization":  ["Orchestration/COST_OPTIMIZER", "General/SPEED_V2", "General/LATENCY_LAYER"],
    "quality":       ["General/QUALITY_QUORUM", "Security/LINT_LEXICON"],
    "recovery":      ["Development/ERROR_RECOVERY", "GIT_PRACTICES/CONFLICT_MAGE"],
    "meta":          ["Orchestration/SKILL_NAVIGATOR", "Orchestration/META_LEARNER"],
    "logging":       ["General/LOG_LEGIONNAIRE", "General/DEBUG_WARLORD"],
    "types":         ["Development/TYPE_TITAN", "Development/CODE_VANGUARD"],
    "streaming":     ["Architecture/KAFKA_MAGE", "Architecture/NETWORK_NOMAD"],
    "audit":         ["Security/AUDITOR", "GIT_PRACTICES/AUDIT_REPORT", "Security/ADVERSARIAL_TESTER"],
}

# Universal skills loaded for ALL interactive sessions
_INTERACTIVE_SKILLS = ["General/DEBUG_WARLORD", "Orchestration/BRAIN_NAVIGATOR"]


def _read_skill(skill_path: str) -> str | None:
    """Read a skill .md file by relative path (e.g. 'Security/AUDITOR')."""
    full = SKILLS_DIR / f"{skill_path}.md"
    if full.exists():
        return full.read_text(encoding="utf-8", errors="replace").strip()
    return None


def load_skills_for_domain(domain: str, max_skills: int = 3, skills_used: bool = False) -> tuple[str, list[str]]:
    """Load actual skill content for a task domain.

    Returns (formatted_content, list_of_skill_filenames).
    """
    if not SKILLS_DIR.exists():
        return "", []

    domain_lower = domain.lower().strip()
    skill_paths = []

    if domain_lower in _DOMAIN_SKILL_MAP:
        skill_paths = _DOMAIN_SKILL_MAP[domain_lower]
    else:
        for key, paths in _DOMAIN_SKILL_MAP.items():
            if key in domain_lower or domain_lower in key:
                skill_paths = paths
                break

    if not skill_paths:
        return "", []

    parts = ["## ACTIVE SKILLS (Auto-loaded for this domain)"]
    loaded_skills = []
    loaded = 0
    for sp in skill_paths[:max_skills]:
        content = _read_skill(sp)
        if content:
            skill_name = sp.split("/")[-1]
            parts.append(f"\n### {skill_name}")
            parts.append(content)
            loaded_skills.append(skill_name)
            loaded += 1

    if loaded == 0:
        return "", []

    tracking_note = ""
    if skills_used:
        skills_str = ",".join(loaded_skills)
        tracking_note = f". MANDATORY: Track usage with `pulse_save.py --skills-used \"{skills_str}\"`"

    parts.append(f"\n(Loaded {loaded} skill(s) for domain: {domain}{tracking_note})")
    return "\n".join(parts), loaded_skills


def load_skills_interactive() -> str:
    """Load universal skills for interactive sessions + index of all available."""
    if not SKILLS_DIR.exists():
        return ""

    parts = ["## SKILLS (Active + Available)"]

    for sp in _INTERACTIVE_SKILLS:
        content = _read_skill(sp)
        if content:
            parts.append(f"\n### {sp.split('/')[-1]} (auto-loaded)")
            parts.append(content)

    parts.append(_build_skills_index_raw())
    parts.append(
        "\nTo activate a domain skill: read the .md file from .cursor/skills/<Category>/<SKILL>.md"
    )

    return "\n".join(parts)


def _build_skills_index_raw() -> str:
    """Build skills index lines (no header)."""
    if not SKILLS_DIR.exists():
        return ""
    lines = ["\nAll available skills:"]
    for category in sorted(SKILLS_DIR.iterdir()):
        if not category.is_dir():
            continue
        skills = sorted(f.stem for f in category.glob("*.md"))
        if skills:
            lines.append(f"  {category.name}: {', '.join(skills)}")
    return "\n".join(lines) if len(lines) > 1 else ""


def _build_skills_index() -> str:
    """Build a compact skills index from .cursor/skills/ for all agents."""
    if not SKILLS_DIR.exists():
        return ""
    lines = ["\nAVAILABLE SKILLS (read the .md file before executing domain tasks):"]
    for category in sorted(SKILLS_DIR.iterdir()):
        if not category.is_dir():
            continue
        skills = sorted(f.stem for f in category.glob("*.md"))
        if skills:
            lines.append(f"  {category.name}: {', '.join(skills)}")
    return "\n".join(lines) if len(lines) > 1 else ""
