#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
Skill Recommender: Smart skill selection based on task content + brain history.

Goes beyond domain mapping — analyzes task description keywords, checks
brain for past skill usage, and recommends the best 2-3 skills.

Usage:
    python skill_recommender.py --task "Fix authentication bug"
    python skill_recommender.py --task "Add REST API endpoint" --json

Dependencies: Python stdlib only (Law 4)
"""

import json
import re
import sys
from pathlib import Path

SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent.parent
SKILLS_DIR = ROOT_DIR / ".cursor" / "skills"

# Keyword → skill mapping (more granular than domain mapping)
_KEYWORD_SKILLS = {
    # Debugging
    "bug": "General/DEBUG_WARLORD",
    "fix": "General/DEBUG_WARLORD",
    "error": "General/DEBUG_WARLORD",
    "crash": "General/DEBUG_WARLORD",
    "debug": "General/DEBUG_WARLORD",
    "broken": "General/DEBUG_WARLORD",
    "failing": "General/DEBUG_WARLORD",
    # Recovery
    "rollback": "Development/ERROR_RECOVERY",
    "revert": "Development/ERROR_RECOVERY",
    "undo": "Development/ERROR_RECOVERY",
    "corrupt": "Development/ERROR_RECOVERY",
    # Security
    "auth": "Security/SECURITY_VANGUARD",
    "security": "Security/SECURITY_VANGUARD",
    "vulnerability": "Security/ADVERSARIAL_TESTER",
    "injection": "Security/ADVERSARIAL_TESTER",
    "xss": "Security/ADVERSARIAL_TESTER",
    "permission": "Security/ZERO_TRUST",
    "encrypt": "Security/SECURITY_VANGUARD",
    # API
    "api": "Development/API_GURU",
    "endpoint": "Development/API_GURU",
    "rest": "Development/API_GURU",
    "graphql": "Development/API_GURU",
    # Database
    "database": "Architecture/DATABASE_WHISPERER",
    "query": "Architecture/DATABASE_WHISPERER",
    "sql": "Architecture/DATABASE_WHISPERER",
    "migration": "Architecture/DATABASE_WHISPERER",
    "index": "Architecture/DATABASE_WHISPERER",
    # Testing
    "test": "Development/TEST_STRATEGIST",
    "coverage": "Development/TEST_STRATEGIST",
    "pytest": "Development/TEST_STRATEGIST",
    "tdd": "Development/TEST_DRIVEN",
    # Refactoring
    "refactor": "Development/REFACTOR_DRUID",
    "cleanup": "Development/REFACTOR_DRUID",
    "simplify": "Architecture/COMPLEXITY_CRUSHER",
    "complexity": "Architecture/COMPLEXITY_CRUSHER",
    # Architecture
    "architect": "Architecture/ARCHITECT",
    "design": "Architecture/ARCHITECT",
    "system": "Architecture/SYSTEM_HARMONIZER",
    "integration": "Architecture/SYSTEM_HARMONIZER",
    # Git
    "commit": "GIT_PRACTICES/COMMIT_ALCHEMIST",
    "merge": "GIT_PRACTICES/CONFLICT_MAGE",
    "branch": "GIT_PRACTICES/GIT_SENTINEL",
    "git": "GIT_PRACTICES/GIT_SENTINEL",
    # DevOps
    "docker": "Development/DOCKER_DRILL",
    "deploy": "Development/CI_CD_COMMANDER",
    "pipeline": "Development/CI_CD_COMMANDER",
    "ci": "Development/CI_CD_COMMANDER",
    # Performance
    "performance": "General/SPEED_V2",
    "slow": "General/SPEED_V2",
    "optimize": "General/SPEED_V2",
    "latency": "General/LATENCY_LAYER",
    "cache": "General/LATENCY_LAYER",
    # UI/UX
    "ui": "Architecture/UI_ALCHEMIST",
    "frontend": "Architecture/UI_ALCHEMIST",
    "ux": "Architecture/UX_PSYCHOLOGIST",
    "accessibility": "Architecture/UX_PSYCHOLOGIST",
    # Data/ML
    "ml": "General/AI_NEUROLOGIST",
    "model": "General/AI_NEUROLOGIST",
    "training": "General/AI_NEUROLOGIST",
    "data": "General/DATA_DYNAMO",
    "etl": "General/DATA_DYNAMO",
    # Documentation
    "doc": "General/DOCU_FORGE",
    "readme": "General/DOC_QUALITY",
    "changelog": "General/DOC_QUALITY",
    # Orchestration
    "orchestr": "Orchestration/ORCHESTRATOR",
    "swarm": "Orchestration/ORCHESTRATOR",
    "brain": "Orchestration/BRAIN_NAVIGATOR",
    "task": "Orchestration/ORCHESTRATOR",
    # Logging
    "log": "General/LOG_LEGIONNAIRE",
    "logging": "General/LOG_LEGIONNAIRE",
    # Cloud
    "cloud": "General/CLOUD_CATALYST",
    "aws": "General/CLOUD_CATALYST",
    "gcp": "General/CLOUD_CATALYST",
    # Types
    "type": "Development/TYPE_TITAN",
    "typescript": "Development/TYPE_TITAN",
    "mypy": "Development/TYPE_TITAN",
}


def recommend(task_description: str, max_skills: int = 3) -> list[dict]:
    """
    Recommend skills for a task based on keyword analysis.

    Args:
        task_description: The task title or description
        max_skills: Maximum number of skills to recommend

    Returns:
        List of {skill, confidence, reason} dicts, sorted by confidence
    """
    task_lower = task_description.lower()
    words = re.findall(r'\b\w+\b', task_lower)

    # Score each skill by keyword hits
    skill_scores: dict[str, dict] = {}

    for word in words:
        # Exact match
        if word in _KEYWORD_SKILLS:
            skill = _KEYWORD_SKILLS[word]
            if skill not in skill_scores:
                skill_scores[skill] = {"hits": 0, "keywords": []}
            skill_scores[skill]["hits"] += 1
            skill_scores[skill]["keywords"].append(word)
        else:
            # Prefix match (e.g., "authenticat" matches "auth")
            for kw, skill in _KEYWORD_SKILLS.items():
                if word.startswith(kw) or kw.startswith(word):
                    if skill not in skill_scores:
                        skill_scores[skill] = {"hits": 0, "keywords": []}
                    skill_scores[skill]["hits"] += 0.5
                    if kw not in skill_scores[skill]["keywords"]:
                        skill_scores[skill]["keywords"].append(kw)

    if not skill_scores:
        # Default recommendation
        return [{
            "skill": "General/DEBUG_WARLORD",
            "confidence": 0.3,
            "reason": "Default safe skill (no specific keywords matched)",
        }]

    # Normalize scores to 0-1 confidence
    max_hits = max(s["hits"] for s in skill_scores.values())
    results = []
    for skill, data in skill_scores.items():
        confidence = round(min(data["hits"] / max(max_hits, 1), 1.0), 2)
        # Verify skill file exists
        skill_path = SKILLS_DIR / f"{skill}.md"
        if not skill_path.exists():
            continue
        results.append({
            "skill": skill,
            "confidence": confidence,
            "reason": f"Keywords: {', '.join(data['keywords'][:3])}",
        })

    # Sort by confidence, take top N
    results.sort(key=lambda x: -x["confidence"])
    return results[:max_skills]


def format_recommendation(results: list[dict]) -> str:
    """Format recommendations for human/agent consumption."""
    if not results:
        return "No skill recommendations available."

    lines = [f"Recommended Skills ({len(results)}):"]
    for i, r in enumerate(results, 1):
        name = r["skill"].split("/")[-1]
        lines.append(f"  {i}. {name} (confidence: {r['confidence']}) — {r['reason']}")
    return "\n".join(lines)


if __name__ == "__main__":
    if "--task" not in sys.argv:
        print("Usage: python skill_recommender.py --task \"Fix authentication bug\" [--json]")
        sys.exit(1)

    idx = sys.argv.index("--task")
    task = sys.argv[idx + 1] if idx + 1 < len(sys.argv) else ""

    results = recommend(task)

    if "--json" in sys.argv:
        print(json.dumps(results, indent=2))
    else:
        print(format_recommendation(results))
