#!/usr/bin/env python3
"""
Research Type Detector - Classify research tasks by TYPE and SOURCE

Types:
1. QUICK_LOOKUP - Simple definitions, known answers (tool: chat)
2. WEB_RESEARCH - External data, current information (tool: web search + thinkdeep)
3. DEEP_RESEARCH - Systematic analysis, hypotheses (tool: thinkdeep)
4. CODE_ANALYSIS - Code review, bugs, performance (tool: codereview, debug)
5. MULTI_PERSPECTIVE - Comparisons, tradeoffs, decisions (tool: consensus)
6. COLLABORATIVE - Team review, audits, assessments (tool: multi-agent)

Detection: Two-dimensional classifier (SCOPE × METHOD)
"""

import re
from typing import List, Dict, Set
from enum import Enum


class ResearchType(Enum):
    """Types of research that can be performed"""
    QUICK_LOOKUP = "quick_lookup"           # Simple answer (chat)
    WEB_RESEARCH = "web_research"           # Needs web data (web + thinkdeep)
    DEEP_RESEARCH = "deep_research"         # Systematic analysis (thinkdeep)
    CODE_ANALYSIS = "code_analysis"         # Code-focused (codereview, debug)
    MULTI_PERSPECTIVE = "multi_perspective" # Comparisons (consensus)
    COLLABORATIVE = "collaborative"         # Team effort (multi-agent)


class ResearchScope(Enum):
    """Scope of research needed"""
    SINGLE_SOURCE = "single_source"         # Quick lookup
    MULTIPLE_SOURCES = "multiple_sources"   # Web + analysis
    SYSTEMATIC = "systematic"               # Deep thinking
    CODE_FOCUSED = "code_focused"           # Code analysis
    COMPARATIVE = "comparative"             # Multiple perspectives
    PARALLEL = "parallel"                   # Collaborative effort


class ResearchTypeDetector:
    """Detect research type from task description"""

    # Keywords that trigger each research type
    QUICK_LOOKUP_KEYWORDS = {
        'what is', 'explain', 'definition', 'define', 'how do i',
        'what does', 'meaning of', 'tell me about', 'simple',
    }

    WEB_RESEARCH_KEYWORDS = {
        'latest', 'current', 'recent', 'trending', 'new',
        'specification', 'standard', 'rfc', 'advisory',
        '2024', '2025', '2026',  # Years indicating recency
        'implementation', 'guide', 'tutorial', 'reference',
        'official', 'documentation', 'whitepaper',
    }

    DEEP_RESEARCH_KEYWORDS = {
        'compare', 'comparison', 'analyze', 'analysis', 'investigate',
        'design', 'architecture', 'evaluate', 'assessment',
        'tradeoff', 'tradeoffs', 'implications', 'impact',
        'why', 'how', 'approach', 'strategy', 'methodology',
        'pattern', 'principle', 'concept', 'theory',
    }

    CODE_ANALYSIS_KEYWORDS = {
        'bug', 'issue', 'error', 'fix', 'problem',
        'performance', 'optimize', 'bottleneck', 'slow',
        'security', 'vulnerability', 'exploit', 'vulnerability',
        'code review', 'review', 'audit', 'test',
        'implementation', 'refactor', 'improve',
    }

    MULTI_PERSPECTIVE_KEYWORDS = {
        'vs', 'vs.', 'versus', 'which', 'better',
        'should we', 'decision', 'choose', 'option',
        'compare', 'comparison', 'alternative', 'tradeoff',
        'pros', 'cons', 'advantage', 'disadvantage',
    }

    COLLABORATIVE_KEYWORDS = {
        'team', 'review', 'audit', 'assessment',
        'multiple', 'experts', 'collaboration', 'collaborative',
        'perspectives', 'feedback', 'approval',
        'design review', 'security assessment', 'code review',
    }

    @staticmethod
    def detect_types(task_description: str) -> List[ResearchType]:
        """
        Detect research types from task description.
        Returns list of types (can be multiple for composite tasks).
        """
        types = set()
        description_lower = task_description.lower()

        # Check each research type
        if ResearchTypeDetector._check_keywords(description_lower, ResearchTypeDetector.WEB_RESEARCH_KEYWORDS):
            types.add(ResearchType.WEB_RESEARCH)

        if ResearchTypeDetector._check_keywords(description_lower, ResearchTypeDetector.DEEP_RESEARCH_KEYWORDS):
            types.add(ResearchType.DEEP_RESEARCH)

        if ResearchTypeDetector._check_keywords(description_lower, ResearchTypeDetector.CODE_ANALYSIS_KEYWORDS):
            types.add(ResearchType.CODE_ANALYSIS)

        if ResearchTypeDetector._check_keywords(description_lower, ResearchTypeDetector.MULTI_PERSPECTIVE_KEYWORDS):
            types.add(ResearchType.MULTI_PERSPECTIVE)

        if ResearchTypeDetector._check_keywords(description_lower, ResearchTypeDetector.COLLABORATIVE_KEYWORDS):
            types.add(ResearchType.COLLABORATIVE)

        if ResearchTypeDetector._check_keywords(description_lower, ResearchTypeDetector.QUICK_LOOKUP_KEYWORDS):
            types.add(ResearchType.QUICK_LOOKUP)

        # If no types detected, default to deep research
        if not types:
            types.add(ResearchType.DEEP_RESEARCH)

        return sorted(list(types), key=lambda x: x.value)

    @staticmethod
    def _check_keywords(text: str, keywords: Set[str]) -> bool:
        """Check if any keywords appear in text"""
        for keyword in keywords:
            if keyword in text:
                return True
        return False

    @staticmethod
    def get_primary_tool(types: List[ResearchType]) -> str:
        """
        Get primary Zen tool for research types.
        For composite types, return coordinating tool.
        """
        if len(types) == 0:
            return "thinkdeep"

        if len(types) == 1:
            type_to_tool = {
                ResearchType.QUICK_LOOKUP: "chat",
                ResearchType.WEB_RESEARCH: "thinkdeep",  # Web search + analysis
                ResearchType.DEEP_RESEARCH: "thinkdeep",
                ResearchType.CODE_ANALYSIS: "codereview",
                ResearchType.MULTI_PERSPECTIVE: "consensus",
                ResearchType.COLLABORATIVE: "planner",  # Coordinates multiple agents
            }
            return type_to_tool.get(types[0], "thinkdeep")

        # Composite type routing
        if ResearchType.COLLABORATIVE in types:
            return "planner"  # Multi-agent orchestrator
        if ResearchType.WEB_RESEARCH in types:
            return "thinkdeep"  # Web research + analysis
        if ResearchType.MULTI_PERSPECTIVE in types:
            return "consensus"  # Multiple perspectives
        if ResearchType.CODE_ANALYSIS in types:
            return "codereview"
        if ResearchType.DEEP_RESEARCH in types:
            return "thinkdeep"

        return "thinkdeep"  # Default

    @staticmethod
    def get_execution_model(types: List[ResearchType]) -> Dict:
        """
        Get execution model for research types.
        Single type: direct execution
        Multiple types: sequential or parallel
        """
        if len(types) <= 1:
            return {
                'type': 'single',
                'parallel': False,
            }

        # Composite execution model
        # Order matters: WEB_RESEARCH → DEEP_RESEARCH → CODE_ANALYSIS → MULTI_PERSPECTIVE → COLLABORATIVE
        execution_order = [
            ResearchType.WEB_RESEARCH,
            ResearchType.DEEP_RESEARCH,
            ResearchType.CODE_ANALYSIS,
            ResearchType.MULTI_PERSPECTIVE,
            ResearchType.COLLABORATIVE,
        ]

        ordered_types = []
        for type_ in execution_order:
            if type_ in types:
                ordered_types.append(type_)

        return {
            'type': 'composite',
            'execution_order': ordered_types,
            'parallel': False,  # Sequential for now, can be optimized
            'coordinate_with': 'thinkdeep',  # Coordinator tool
        }

    @staticmethod
    def get_description(types: List[ResearchType]) -> str:
        """Get human-readable description of research task"""
        if not types:
            return "Deep research analysis"

        type_descriptions = {
            ResearchType.QUICK_LOOKUP: "Quick lookup",
            ResearchType.WEB_RESEARCH: "Web research",
            ResearchType.DEEP_RESEARCH: "Deep analysis",
            ResearchType.CODE_ANALYSIS: "Code analysis",
            ResearchType.MULTI_PERSPECTIVE: "Multi-perspective comparison",
            ResearchType.COLLABORATIVE: "Collaborative assessment",
        }

        descriptions = [type_descriptions.get(t, t.value) for t in types]

        if len(descriptions) == 1:
            return descriptions[0]
        elif len(descriptions) == 2:
            return f"{descriptions[0]} + {descriptions[1]}"
        else:
            return f"{', '.join(descriptions[:-1])} + {descriptions[-1]}"


class ResearchComposer:
    """Compose multiple research types for complex tasks"""

    @staticmethod
    def compose_execution(types: List[ResearchType], task_description: str) -> Dict:
        """
        Create execution plan for composite research tasks.
        """
        model = ResearchTypeDetector.get_execution_model(types)

        if model['type'] == 'single':
            return {
                'task': task_description,
                'types': types,
                'primary_tool': ResearchTypeDetector.get_primary_tool(types),
                'description': ResearchTypeDetector.get_description(types),
                'steps': 1,
            }

        # Composite execution plan
        steps = []

        if ResearchType.WEB_RESEARCH in types:
            steps.append({
                'step': 1,
                'type': ResearchType.WEB_RESEARCH,
                'action': 'Gather external data (web search, documentation)',
            })

        if ResearchType.DEEP_RESEARCH in types:
            steps.append({
                'step': len(steps) + 1,
                'type': ResearchType.DEEP_RESEARCH,
                'action': 'Systematic analysis of gathered information',
            })

        if ResearchType.CODE_ANALYSIS in types:
            steps.append({
                'step': len(steps) + 1,
                'type': ResearchType.CODE_ANALYSIS,
                'action': 'Code review and analysis',
            })

        if ResearchType.MULTI_PERSPECTIVE in types:
            steps.append({
                'step': len(steps) + 1,
                'type': ResearchType.MULTI_PERSPECTIVE,
                'action': 'Multi-perspective comparison and evaluation',
            })

        if ResearchType.COLLABORATIVE in types:
            steps.append({
                'step': len(steps) + 1,
                'type': ResearchType.COLLABORATIVE,
                'action': 'Collaborative review and assessment',
            })

        return {
            'task': task_description,
            'types': types,
            'description': ResearchTypeDetector.get_description(types),
            'execution_plan': steps,
            'total_steps': len(steps),
            'coordinator_tool': 'thinkdeep',
        }


if __name__ == '__main__':
    # Test detection
    test_tasks = [
        "quick answer: what is OAuth?",
        "latest OAuth 2.1 specification and implementations",
        "analyze and compare REST vs GraphQL for our API",
        "review authentication implementation for security issues",
        "design new caching architecture with team review",
        "what is the difference between SQL and NoSQL?",
        "latest security vulnerabilities in Django framework",
        "why is performance slow in production?",
        "should we use microservices or monolith?",
    ]

    print("=" * 80)
    print("RESEARCH TYPE DETECTION - DEMONSTRATION")
    print("=" * 80)

    for task in test_tasks:
        types = ResearchTypeDetector.detect_types(task)
        tool = ResearchTypeDetector.get_primary_tool(types)
        execution = ResearchComposer.compose_execution(types, task)

        print(f"\n📋 Task: {task}")
        print(f"   Types: {[t.value for t in types]}")
        print(f"   Primary Tool: {tool}")
        print(f"   Description: {execution['description']}")

        if execution.get('execution_plan'):
            print(f"   Execution Plan ({execution['total_steps']} steps):")
            for step in execution['execution_plan']:
                print(f"     Step {step['step']}: {step['action']}")
