#!/usr/bin/env python3
"""
Skill Router - Auto-detect and load skills based on context

Usage:
    python3 skill-router.py test "메시지 내용"
    python3 skill-router.py detect "메시지 내용" --task-type coding
"""

import json
import os
import re
import sys
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional

# autoresearch capture hook (optional - failures are silently ignored)
try:
    _ws_root = str(Path(__file__).parent.parent)
    if _ws_root not in sys.path:
        sys.path.insert(0, _ws_root)
    from scripts.autoresearch.capture import capture_input as _capture_input
except Exception:
    _capture_input = None  # type: ignore[assignment]


class SkillRouter:
    """Auto-detect and load skills based on context analysis"""

    def __init__(self, triggers_path: Optional[str] = None, workspace_path: Optional[str] = None):
        """
        Initialize SkillRouter

        Args:
            triggers_path: Path to skill-triggers.json (defaults to same directory)
            workspace_path: Path to workspace (defaults to parent of memory directory)
        """
        if triggers_path is None:
            triggers_path = Path(__file__).parent / "skill-triggers.json"

        if workspace_path is None:
            workspace_path = Path(__file__).parent.parent

        self.triggers_path = Path(triggers_path)
        self.workspace_path = Path(workspace_path)
        self.triggers: List[Dict] = []
        self.loaded_skills: Dict[str, Any] = {}

    def load_triggers(self) -> bool:
        """
        Load trigger definitions from JSON file

        Returns:
            True if loaded successfully, False otherwise
        """
        try:
            if not self.triggers_path.exists():
                print(f"⚠️  Triggers file not found: {self.triggers_path}")
                return False

            with open(self.triggers_path, "r", encoding="utf-8") as f:
                data = json.load(f)

            self.triggers = data.get("triggers", [])
            print(f"✅ Loaded {len(self.triggers)} skill triggers")
            return True

        except Exception as e:
            print(f"❌ Error loading triggers: {e}")
            return False

    def matches_conditions(self, context: Dict, conditions: List[Dict]) -> bool:
        """
        Check if context matches all conditions

        Args:
            context: Dict with 'message', 'task_type', 'keywords', etc.
            conditions: List of condition dicts to match

        Returns:
            True if all conditions match, False otherwise
        """
        message = context.get("message", "").lower()
        task_type = context.get("task_type", "").lower()

        for condition in conditions:
            cond_type = condition.get("type")

            if cond_type == "keyword":
                patterns = condition.get("patterns", [])
                if not any(pattern.lower() in message for pattern in patterns):
                    return False

            elif cond_type == "task_type":
                types = condition.get("types", [])
                if task_type and task_type not in [t.lower() for t in types]:
                    return False

        return True

    def detect_and_load_skills(self, context: Dict) -> List[Dict]:
        """
        Detect which skills match the context and optionally load them

        Args:
            context: Dict with 'message', 'task_type', 'keywords', etc.

        Returns:
            List of matched skill info dicts
        """
        if not self.triggers:
            self.load_triggers()

        matched_skills = []

        for trigger in self.triggers:
            skill_name = trigger.get("skill")
            conditions = trigger.get("conditions", [])
            auto_load = trigger.get("auto_load", False)
            priority = trigger.get("priority", "medium")

            if self.matches_conditions(context, conditions):
                skill_info = {"skill": skill_name, "priority": priority, "auto_load": auto_load}
                matched_skills.append(skill_info)

                try:
                    if _capture_input is not None and isinstance(skill_name, str):
                        _capture_input(skill_name, context.get("message", ""))
                except Exception:
                    pass

                if auto_load:
                    self.load_skill(skill_name)

        # Sort by priority (high > medium > low)
        priority_order = {"high": 0, "medium": 1, "low": 2}
        matched_skills.sort(key=lambda x: priority_order.get(x["priority"], 1))

        return matched_skills

    def load_skill(self, skill_name: str) -> bool:
        """
        Load a skill by reading its SKILL.md file

        Args:
            skill_name: Name of the skill to load

        Returns:
            True if loaded successfully, False otherwise
        """
        if skill_name in self.loaded_skills:
            print(f"   ℹ️  Skill '{skill_name}' already loaded")
            return True

        # 1. SKILL.md 파일 찾기 (플랫 구조: ai-organization/skills/{skill_name}.md)
        skill_path = self.workspace_path / "ai-organization" / "skills" / f"{skill_name}.md"

        # 2. 파일이 있으면 읽기
        if skill_path.exists():
            try:
                with open(skill_path, "r", encoding="utf-8") as f:
                    skill_content = f.read()

                # 3. skill 내용 저장
                self.loaded_skills[skill_name] = {
                    "name": skill_name,
                    "content": skill_content,
                    "loaded_at": datetime.now().isoformat(),
                }

                print(f"   ✅ Skill 로드됨: {skill_name}")
                return True
            except Exception as e:
                print(f"   ❌ Skill 로드 실패 ({skill_name}): {e}")
                return False
        else:
            print(f"   ⚠️  Skill 파일 없음: {skill_path}")
            return False

    def get_loaded_skills(self) -> List[str]:
        """Get list of loaded skill names"""
        return list(self.loaded_skills.keys())


def main():
    """CLI interface for testing"""

    if len(sys.argv) < 3:
        print(__doc__)
        sys.exit(1)

    command = sys.argv[1]

    if command == "test":
        # Simple test with message
        message = sys.argv[2] if len(sys.argv) > 2 else ""

        router = SkillRouter()
        router.load_triggers()

        context = {"message": message, "task_type": ""}

        print(f'\n🔍 Analyzing: "{message}"\n')
        matched = router.detect_and_load_skills(context)

        if matched:
            print(f"\n✅ Matched {len(matched)} skill(s):")
            for skill in matched:
                print(f"   • {skill['skill']} (priority: {skill['priority']}, auto_load: {skill['auto_load']})")
        else:
            print("\n⚠️  No skills matched this context")

        print(f"\n📚 Loaded skills: {router.get_loaded_skills()}")

    elif command == "detect":
        # Advanced detection with task type
        message = sys.argv[2] if len(sys.argv) > 2 else ""
        task_type = ""

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

        router = SkillRouter()
        router.load_triggers()

        context = {"message": message, "task_type": task_type}

        print(f"\n🔍 Analyzing:")
        print(f'   Message: "{message}"')
        print(f'   Task type: "{task_type}"\n')

        matched = router.detect_and_load_skills(context)

        if matched:
            print(f"\n✅ Matched {len(matched)} skill(s):")
            for skill in matched:
                print(f"   • {skill['skill']} (priority: {skill['priority']}, auto_load: {skill['auto_load']})")
        else:
            print("\n⚠️  No skills matched this context")

        print(f"\n📚 Loaded skills: {router.get_loaded_skills()}")

    else:
        print(f"Unknown command: {command}")
        print(__doc__)
        sys.exit(1)


if __name__ == "__main__":
    main()
