"""
AI Knowledge Taxonomy for Self-Aware Worthiness Judgment.

Defines comprehensive taxonomies of AI blind spots and AI common sense,
enabling AI to understand its own knowledge boundaries and what should be stored.

Philosophy:
AI should distinguish between:
1. AI Blind Spots (需要记录) - Knowledge that fills gaps and improves conversation quality
2. AI Common Sense (无需记录) - Knowledge that AI already knows and won't improve quality
"""

from typing import List, Dict, Any, Optional, Set
from dataclasses import dataclass
from enum import Enum


class KnowledgeCategory(Enum):
    """High-level categories for knowledge classification."""
    BLIND_SPOT = "blind_spot"      # AI needs to learn this
    COMMON_SENSE = "common_sense"  # AI already knows this
    UNCERTAIN = "uncertain"         # AI is unsure about its boundaries


@dataclass
class TaxonomyNode:
    """A node in the knowledge taxonomy tree."""
    name: str
    description: str
    category: KnowledgeCategory
    detection_keywords: List[str]
    detection_patterns: List[str]
    examples_positive: List[str]  # Examples that match
    examples_negative: List[str]  # Examples that don't match
    confidence_weight: float       # How confident is this classification (0.0-1.0)
    children: List['TaxonomyNode'] = None

    def __post_init__(self):
        if self.children is None:
            self.children = []


class AIBlindSpotsTaxonomy:
    """
    Taxonomy of AI Blind Spots - Knowledge that AI should store.

    These are areas where AI systematically struggles or lacks information,
    and storing this knowledge will improve future conversation quality.
    """

    @staticmethod
    def get_taxonomy() -> List[TaxonomyNode]:
        """Get complete AI blind spots taxonomy."""
        return [
            # Category 1: User-Specific Context
            TaxonomyNode(
                name="user_specific_context",
                description="User's personal preferences, habits, workflow, and style that AI cannot infer",
                category=KnowledgeCategory.BLIND_SPOT,
                detection_keywords=["prefer", "usually", "always", "never", "my style", "I like", "I want"],
                detection_patterns=[
                    r"I (prefer|like|want|need|expect) .+",
                    r"(always|never|usually) .+ when .+",
                    r"my (style|preference|workflow|habit)"
                ],
                examples_positive=[
                    "I prefer snake_case for variables",
                    "Always add TODO comments for unfinished work",
                    "I like verbose commit messages with context"
                ],
                examples_negative=[
                    "Use camelCase in JavaScript",  # This is language convention, not personal
                    "Add error handling"  # This is best practice, not preference
                ],
                confidence_weight=0.95,
                children=[
                    TaxonomyNode(
                        name="coding_style_preferences",
                        description="Personal coding style beyond language conventions",
                        category=KnowledgeCategory.BLIND_SPOT,
                        detection_keywords=["style", "format", "indent", "naming"],
                        detection_patterns=[r"(prefer|use) .+ (style|format|naming)"],
                        examples_positive=["Use 2 spaces, not 4", "Max line length 100"],
                        examples_negative=["Use semicolons in JavaScript"],
                        confidence_weight=0.90
                    ),
                    TaxonomyNode(
                        name="workflow_preferences",
                        description="How user prefers to work and organize tasks",
                        category=KnowledgeCategory.BLIND_SPOT,
                        detection_keywords=["workflow", "process", "organize", "structure"],
                        detection_patterns=[r"I (work|organize|structure) .+ by .+"],
                        examples_positive=["Create feature branches from develop, not main"],
                        examples_negative=["Use git branches"],
                        confidence_weight=0.90
                    ),
                    TaxonomyNode(
                        name="communication_style",
                        description="How user prefers AI to communicate",
                        category=KnowledgeCategory.BLIND_SPOT,
                        detection_keywords=["explain", "detailed", "brief", "concise", "verbose"],
                        detection_patterns=[r"(be more|less) (detailed|verbose|concise)"],
                        examples_positive=["Explain your reasoning before showing code"],
                        examples_negative=["Use clear variable names"],
                        confidence_weight=0.85
                    )
                ]
            ),

            # Category 2: Project-Specific Knowledge
            TaxonomyNode(
                name="project_specific_knowledge",
                description="Project architecture, conventions, and decisions not visible in code",
                category=KnowledgeCategory.BLIND_SPOT,
                detection_keywords=["this project", "our codebase", "we decided", "architecture"],
                detection_patterns=[
                    r"(this project|our codebase) (uses|follows|implements) .+",
                    r"we (decided|chose|use) .+ because .+"
                ],
                examples_positive=[
                    "In this project, utils/ is for pure functions only",
                    "We use Redux for state because team knows it well"
                ],
                examples_negative=[
                    "Use React for UI",  # Generic, not project-specific
                    "Put utilities in utils/"  # Generic convention
                ],
                confidence_weight=0.90,
                children=[
                    TaxonomyNode(
                        name="architecture_decisions",
                        description="Why certain architectural choices were made",
                        category=KnowledgeCategory.BLIND_SPOT,
                        detection_keywords=["decided", "chose", "because", "reason"],
                        detection_patterns=[r"(decided|chose) .+ because .+"],
                        examples_positive=["Chose MongoDB because data is unstructured"],
                        examples_negative=["Use a database"],
                        confidence_weight=0.92
                    ),
                    TaxonomyNode(
                        name="non_obvious_conventions",
                        description="Project conventions that differ from standard practices",
                        category=KnowledgeCategory.BLIND_SPOT,
                        detection_keywords=["convention", "rule", "always", "never", "must"],
                        detection_patterns=[r"(always|never|must) .+ in this (project|codebase)"],
                        examples_positive=["Test files must end with .test.ts, not .spec.ts"],
                        examples_negative=["Write unit tests"],
                        confidence_weight=0.88
                    ),
                    TaxonomyNode(
                        name="gotchas_and_traps",
                        description="Project-specific edge cases and pitfalls",
                        category=KnowledgeCategory.BLIND_SPOT,
                        detection_keywords=["careful", "watch out", "gotcha", "trap", "pitfall"],
                        detection_patterns=[r"(watch out|be careful|gotcha|trap)"],
                        examples_positive=["Don't import from src/legacy - it breaks builds"],
                        examples_negative=["Avoid circular dependencies"],
                        confidence_weight=0.93
                    )
                ]
            ),

            # Category 3: Counter-Intuitive Knowledge
            TaxonomyNode(
                name="counter_intuitive_knowledge",
                description="Knowledge that contradicts common patterns or AI's training data",
                category=KnowledgeCategory.BLIND_SPOT,
                detection_keywords=["actually", "contrary", "opposite", "not", "don't"],
                detection_patterns=[
                    r"(actually|surprisingly|contrary to) .+",
                    r"(don't|do not) .+ (instead|rather|use) .+"
                ],
                examples_positive=[
                    "For this API, PUT is idempotent but POST is not",
                    "Don't use async/await here - callbacks are faster due to event loop"
                ],
                examples_negative=[
                    "Use async/await for promises",  # Standard practice
                    "REST APIs use HTTP methods"  # Common knowledge
                ],
                confidence_weight=0.88,
                children=[
                    TaxonomyNode(
                        name="performance_counter_intuition",
                        description="Performance optimizations that go against obvious approaches",
                        category=KnowledgeCategory.BLIND_SPOT,
                        detection_keywords=["faster", "slower", "performance", "optimize"],
                        detection_patterns=[r"(faster|slower|better performance) .+ (than|instead)"],
                        examples_positive=["Array.forEach is slower than for-loop here due to JIT"],
                        examples_negative=["Use memoization for performance"],
                        confidence_weight=0.85
                    ),
                    TaxonomyNode(
                        name="semantic_subtleties",
                        description="Subtle semantic differences AI easily overlooks",
                        category=KnowledgeCategory.BLIND_SPOT,
                        detection_keywords=["subtle", "difference", "distinction", "not the same"],
                        detection_patterns=[r"(subtle|important) (difference|distinction) between"],
                        examples_positive=["In this API, 'null' means missing, 'undefined' means not computed yet"],
                        examples_negative=["null and undefined are different"],
                        confidence_weight=0.87
                    )
                ]
            ),

            # Category 4: User Corrections
            TaxonomyNode(
                name="user_corrections",
                description="Instances where AI made a mistake and user corrected it",
                category=KnowledgeCategory.BLIND_SPOT,
                detection_keywords=["wrong", "incorrect", "mistake", "should be", "actually"],
                detection_patterns=[
                    r"(that's|that is) (wrong|incorrect|not right)",
                    r"(should be|actually|supposed to be) .+ (not|instead)"
                ],
                examples_positive=[
                    "That's wrong - the function returns null, not undefined",
                    "No, we use POST for this endpoint, not PUT"
                ],
                examples_negative=[
                    "Fix the typo",  # Generic correction
                    "Add error handling"  # Generic improvement
                ],
                confidence_weight=0.98,  # Very high - user explicitly corrected AI
                children=[
                    TaxonomyNode(
                        name="factual_corrections",
                        description="AI stated wrong facts",
                        category=KnowledgeCategory.BLIND_SPOT,
                        detection_keywords=["wrong", "incorrect", "not true"],
                        detection_patterns=[r"(that's|that is) (wrong|incorrect|false)"],
                        examples_positive=["This library doesn't support async - you're wrong"],
                        examples_negative=["Fix the syntax"],
                        confidence_weight=0.99
                    ),
                    TaxonomyNode(
                        name="behavioral_corrections",
                        description="AI's approach or behavior was wrong",
                        category=KnowledgeCategory.BLIND_SPOT,
                        detection_keywords=["don't", "shouldn't", "stop"],
                        detection_patterns=[r"(don't|do not|stop) .+ (instead|use)"],
                        examples_positive=["Don't use regex for parsing HTML - use a parser"],
                        examples_negative=["Don't write buggy code"],
                        confidence_weight=0.96
                    )
                ]
            ),

            # Category 5: Edge Cases and Traps
            TaxonomyNode(
                name="edge_cases_and_traps",
                description="Non-obvious edge cases, gotchas, and pitfalls that AI misses",
                category=KnowledgeCategory.BLIND_SPOT,
                detection_keywords=["edge case", "gotcha", "trap", "careful", "pitfall"],
                detection_patterns=[
                    r"(edge case|gotcha|trap|pitfall)",
                    r"(watch out|be careful|beware)"
                ],
                examples_positive=[
                    "Edge case: when array is empty, reduce throws without initial value",
                    "Gotcha: setTimeout callback loses 'this' context"
                ],
                examples_negative=[
                    "Handle errors",  # Generic
                    "Check for null"  # Generic
                ],
                confidence_weight=0.91
            ),

            # Category 6: Recent Changes (Post-Cutoff)
            TaxonomyNode(
                name="recent_changes",
                description="Technology changes, updates, or new features after AI's knowledge cutoff",
                category=KnowledgeCategory.BLIND_SPOT,
                detection_keywords=["new", "recently", "updated", "changed", "latest", "now"],
                detection_patterns=[
                    r"(new|recent|latest) (version|update|feature|release)",
                    r"(now|recently) (supports|changed|updated)"
                ],
                examples_positive=[
                    "React 19 now has built-in compiler - no need for memo",
                    "Node 22 changed default behavior of fetch timeout"
                ],
                examples_negative=[
                    "Use the latest version",  # Generic advice
                    "Update dependencies"  # Generic maintenance
                ],
                confidence_weight=0.94
            ),

            # Category 7: Domain-Specific Deep Knowledge
            TaxonomyNode(
                name="domain_specific_deep_knowledge",
                description="Deep domain expertise beyond AI's general training",
                category=KnowledgeCategory.BLIND_SPOT,
                detection_keywords=["advanced", "expert", "deep", "specialized", "domain"],
                detection_patterns=[r"(advanced|expert|deep|specialized) .+ (technique|pattern|approach)"],
                examples_positive=[
                    "In computational geometry, use spatial hashing for collision detection",
                    "For high-frequency trading, use FIX protocol, not REST"
                ],
                examples_negative=[
                    "Use appropriate algorithms",  # Generic
                    "Follow best practices"  # Generic
                ],
                confidence_weight=0.83
            ),

            # Category 8: Cross-Domain Connections
            TaxonomyNode(
                name="cross_domain_connections",
                description="Non-obvious connections between domains that AI struggles to infer",
                category=KnowledgeCategory.BLIND_SPOT,
                detection_keywords=["similar to", "like", "related to", "inspired by"],
                detection_patterns=[r"(similar to|like|related to|inspired by) .+ (from|in) .+"],
                examples_positive=[
                    "This state management pattern is similar to Redux but for backend",
                    "Use backpressure like reactive streams do"
                ],
                examples_negative=[
                    "This is like the singleton pattern",  # Common pattern
                    "Similar to a queue"  # Basic data structure
                ],
                confidence_weight=0.80
            ),

            # Category 9: Security/Performance Pitfalls
            TaxonomyNode(
                name="security_performance_pitfalls",
                description="Code that looks correct but has security/performance issues",
                category=KnowledgeCategory.BLIND_SPOT,
                detection_keywords=["security", "vulnerability", "performance", "slow", "unsafe"],
                detection_patterns=[
                    r"(security|vulnerability|unsafe|insecure)",
                    r"(slow|performance issue|bottleneck)"
                ],
                examples_positive=[
                    "Don't use eval() - it's a security risk even with sanitized input",
                    "This RegEx causes catastrophic backtracking on large strings"
                ],
                examples_negative=[
                    "Sanitize user input",  # Generic security advice
                    "Optimize performance"  # Generic advice
                ],
                confidence_weight=0.92
            ),

            # Category 10: Explicit Memory Requests
            TaxonomyNode(
                name="explicit_memory_requests",
                description="User explicitly asks AI to remember something",
                category=KnowledgeCategory.BLIND_SPOT,
                detection_keywords=["remember", "note", "keep in mind", "don't forget"],
                detection_patterns=[
                    r"(remember|note|keep in mind|don't forget) (that|this)",
                    r"(save|store|record) this (for|in)"
                ],
                examples_positive=[
                    "Remember: I prefer TypeScript over JavaScript",
                    "Note that we deploy on Fridays only"
                ],
                examples_negative=[
                    "Remember to add tests",  # Generic reminder
                    "Don't forget error handling"  # Generic reminder
                ],
                confidence_weight=0.97  # User explicitly requested
            )
        ]

    @staticmethod
    def detect_blind_spot_category(text: str) -> Optional[Dict[str, Any]]:
        """
        Detect if text matches any AI blind spot category.

        Returns:
            Dict with keys: category, confidence, reasoning
            None if no match
        """
        import re

        text_lower = text.lower()
        taxonomy = AIBlindSpotsTaxonomy.get_taxonomy()

        matches = []

        def check_node(node: TaxonomyNode, depth: int = 0):
            """Recursively check node and children."""
            score = 0.0
            reasons = []

            # Keyword matching
            keyword_matches = [kw for kw in node.detection_keywords if kw in text_lower]
            if keyword_matches:
                score += 0.3 * (len(keyword_matches) / len(node.detection_keywords))
                reasons.append(f"Keywords: {', '.join(keyword_matches)}")

            # Pattern matching
            for pattern in node.detection_patterns:
                if re.search(pattern, text, re.IGNORECASE):
                    score += 0.5
                    reasons.append(f"Pattern matched: {pattern}")
                    break

            # Check positive examples similarity (simple heuristic)
            for example in node.examples_positive:
                if len(set(text_lower.split()) & set(example.lower().split())) > 3:
                    score += 0.2
                    reasons.append(f"Similar to: {example[:50]}...")
                    break

            if score > 0:
                matches.append({
                    'node': node,
                    'score': score * node.confidence_weight,
                    'depth': depth,
                    'reasons': reasons
                })

            # Check children
            for child in node.children:
                check_node(child, depth + 1)

        # Check all taxonomy nodes
        for root_node in taxonomy:
            check_node(root_node)

        if not matches:
            return None

        # Return best match
        best_match = max(matches, key=lambda m: m['score'])
        node = best_match['node']

        return {
            'category': node.name,
            'description': node.description,
            'confidence': min(best_match['score'], 1.0),
            'reasoning': "; ".join(best_match['reasons']),
            'is_blind_spot': True
        }


class AICommonSenseTaxonomy:
    """
    Taxonomy of AI Common Sense - Knowledge that AI should NOT store.

    These are areas where AI already has strong general knowledge,
    and storing this won't improve conversation quality.
    """

    @staticmethod
    def get_taxonomy() -> List[TaxonomyNode]:
        """Get complete AI common sense taxonomy."""
        return [
            # Category 1: Basic Language Syntax
            TaxonomyNode(
                name="basic_language_syntax",
                description="Fundamental syntax of programming languages",
                category=KnowledgeCategory.COMMON_SENSE,
                detection_keywords=["syntax", "how to", "basic", "fundamental"],
                detection_patterns=[
                    r"how (to|do I) (write|create|define|declare) .+ in .+",
                    r"(syntax|basic|fundamental) .+ (in|for) .+"
                ],
                examples_positive=[
                    "How to declare a variable in Python",
                    "JavaScript function syntax",
                    "Python uses indentation for blocks"
                ],
                examples_negative=[
                    "How we structure error handling in this project",  # Project-specific
                    "Our custom function naming convention"  # Project-specific
                ],
                confidence_weight=0.95
            ),

            # Category 2: Well-Documented APIs
            TaxonomyNode(
                name="well_documented_apis",
                description="Standard library and popular framework APIs with extensive docs",
                category=KnowledgeCategory.COMMON_SENSE,
                detection_keywords=["api", "library", "framework", "method", "function"],
                detection_patterns=[
                    r"(standard library|built-in) (function|method|api)",
                    r"(popular|well-known|standard) (framework|library)"
                ],
                examples_positive=[
                    "Array.map() in JavaScript",
                    "useState hook in React",
                    "requests.get() in Python"
                ],
                examples_negative=[
                    "Our custom API wrapper for requests",  # Custom, not standard
                    "Modified useState hook we created"  # Custom
                ],
                confidence_weight=0.92
            ),

            # Category 3: Common Design Patterns
            TaxonomyNode(
                name="common_design_patterns",
                description="Well-known design patterns from Gang of Four and similar",
                category=KnowledgeCategory.COMMON_SENSE,
                detection_keywords=["pattern", "singleton", "factory", "observer", "strategy"],
                detection_patterns=[
                    r"(singleton|factory|observer|strategy|decorator) pattern",
                    r"(design pattern|common pattern)"
                ],
                examples_positive=[
                    "Singleton pattern",
                    "Factory pattern",
                    "Observer pattern for events"
                ],
                examples_negative=[
                    "Our custom event pattern",  # Custom variation
                    "Project-specific factory implementation"  # Project-specific
                ],
                confidence_weight=0.90
            ),

            # Category 4: Basic Algorithms and Data Structures
            TaxonomyNode(
                name="basic_algorithms_data_structures",
                description="Common algorithms and data structures from CS fundamentals",
                category=KnowledgeCategory.COMMON_SENSE,
                detection_keywords=["algorithm", "data structure", "sort", "search", "tree", "graph"],
                detection_patterns=[
                    r"(sorting|searching|traversal) algorithm",
                    r"(array|list|tree|graph|hash|stack|queue) (data structure|implementation)"
                ],
                examples_positive=[
                    "Binary search algorithm",
                    "Quicksort implementation",
                    "Binary tree traversal"
                ],
                examples_negative=[
                    "Our custom sorting logic for products",  # Domain-specific
                    "Project-specific tree structure"  # Project-specific
                ],
                confidence_weight=0.93
            ),

            # Category 5: Math and Logic Fundamentals
            TaxonomyNode(
                name="math_logic_fundamentals",
                description="Basic mathematics, logic, and computational principles",
                category=KnowledgeCategory.COMMON_SENSE,
                detection_keywords=["math", "formula", "logic", "equation", "calculate"],
                detection_patterns=[
                    r"(basic|simple) (math|formula|equation)",
                    r"(calculate|compute) .+ (using|with) .+"
                ],
                examples_positive=[
                    "Calculate average of array",
                    "Pythagorean theorem",
                    "Boolean logic operators"
                ],
                examples_negative=[
                    "Our custom pricing formula",  # Domain-specific
                    "Project-specific calculation"  # Project-specific
                ],
                confidence_weight=0.94
            ),

            # Category 6: Generic Best Practices
            TaxonomyNode(
                name="generic_best_practices",
                description="Universal best practices applicable to all projects",
                category=KnowledgeCategory.COMMON_SENSE,
                detection_keywords=["best practice", "should", "recommended", "good practice"],
                detection_patterns=[
                    r"(best practice|good practice|recommended) .+ (to|is|for)",
                    r"(should|must|always|never) .+ (as a best practice)"
                ],
                examples_positive=[
                    "Use meaningful variable names",
                    "Write unit tests",
                    "Handle errors gracefully"
                ],
                examples_negative=[
                    "We always add debug logs to API calls",  # Project-specific
                    "Must use try-catch in all async functions here"  # Project-specific
                ],
                confidence_weight=0.88
            ),

            # Category 7: One-Time Information
            TaxonomyNode(
                name="one_time_information",
                description="Information only relevant to current conversation",
                category=KnowledgeCategory.COMMON_SENSE,
                detection_keywords=["now", "currently", "right now", "at the moment"],
                detection_patterns=[
                    r"(right now|currently|at the moment|just now)",
                    r"(this time|this conversation)"
                ],
                examples_positive=[
                    "I'm currently working on authentication",
                    "Right now, focus on the login page",
                    "At the moment, skip tests"
                ],
                examples_negative=[
                    "We always skip integration tests during development",  # General practice
                    "Currently, our architecture is microservices"  # Persistent state
                ],
                confidence_weight=0.85
            ),

            # Category 8: Obvious Consequences
            TaxonomyNode(
                name="obvious_consequences",
                description="Trivially obvious cause-effect relationships",
                category=KnowledgeCategory.COMMON_SENSE,
                detection_keywords=["if", "then", "causes", "results in", "leads to"],
                detection_patterns=[
                    r"if .+ then .+ (obviously|clearly)",
                    r".+ (causes|results in|leads to) .+ (obviously|of course)"
                ],
                examples_positive=[
                    "If you don't close files, it causes memory leaks",
                    "Null pointer causes crashes",
                    "Missing semicolons cause syntax errors"
                ],
                examples_negative=[
                    "In this codebase, missing auth checks cause silent failures",  # Project-specific
                    "Our API returns 200 even on errors"  # Non-obvious, project-specific
                ],
                confidence_weight=0.87
            ),

            # Category 9: Tool/Command Basic Usage
            TaxonomyNode(
                name="tool_command_basic_usage",
                description="Basic usage of common development tools and commands",
                category=KnowledgeCategory.COMMON_SENSE,
                detection_keywords=["command", "tool", "git", "npm", "docker"],
                detection_patterns=[
                    r"(git|npm|docker|pip|cargo) (command|usage|basic)",
                    r"how to (use|run) .+ (git|npm|docker)"
                ],
                examples_positive=[
                    "git commit creates a commit",
                    "npm install installs dependencies",
                    "docker run starts a container"
                ],
                examples_negative=[
                    "Our git workflow requires squashing",  # Project-specific workflow
                    "We use custom npm scripts for deployment"  # Project-specific
                ],
                confidence_weight=0.91
            ),

            # Category 10: Natural Language Basics
            TaxonomyNode(
                name="natural_language_basics",
                description="Basic grammar, vocabulary, and language conventions",
                category=KnowledgeCategory.COMMON_SENSE,
                detection_keywords=["grammar", "spelling", "vocabulary", "word", "phrase"],
                detection_patterns=[
                    r"(grammar|spelling|vocabulary|language) (rule|basic)",
                    r"what (does|is) .+ (mean|definition)"
                ],
                examples_positive=[
                    "Grammar rules for English",
                    "What does 'iterate' mean",
                    "Difference between 'effect' and 'affect'"
                ],
                examples_negative=[
                    "In our docs, use 'finalize' not 'complete'",  # Project-specific terminology
                    "We use British spelling in code"  # Project-specific convention
                ],
                confidence_weight=0.93
            )
        ]

    @staticmethod
    def detect_common_sense_category(text: str) -> Optional[Dict[str, Any]]:
        """
        Detect if text matches any AI common sense category.

        Returns:
            Dict with keys: category, confidence, reasoning
            None if no match
        """
        import re

        text_lower = text.lower()
        taxonomy = AICommonSenseTaxonomy.get_taxonomy()

        matches = []

        def check_node(node: TaxonomyNode, depth: int = 0):
            """Recursively check node and children."""
            score = 0.0
            reasons = []

            # Keyword matching
            keyword_matches = [kw for kw in node.detection_keywords if kw in text_lower]
            if keyword_matches:
                score += 0.3 * (len(keyword_matches) / len(node.detection_keywords))
                reasons.append(f"Keywords: {', '.join(keyword_matches)}")

            # Pattern matching
            for pattern in node.detection_patterns:
                if re.search(pattern, text, re.IGNORECASE):
                    score += 0.5
                    reasons.append(f"Pattern matched: {pattern}")
                    break

            # Check positive examples similarity
            for example in node.examples_positive:
                if len(set(text_lower.split()) & set(example.lower().split())) > 3:
                    score += 0.2
                    reasons.append(f"Similar to: {example[:50]}...")
                    break

            if score > 0:
                matches.append({
                    'node': node,
                    'score': score * node.confidence_weight,
                    'depth': depth,
                    'reasons': reasons
                })

            # Check children
            for child in node.children:
                check_node(child, depth + 1)

        # Check all taxonomy nodes
        for root_node in taxonomy:
            check_node(root_node)

        if not matches:
            return None

        # Return best match
        best_match = max(matches, key=lambda m: m['score'])
        node = best_match['node']

        return {
            'category': node.name,
            'description': node.description,
            'confidence': min(best_match['score'], 1.0),
            'reasoning': "; ".join(best_match['reasons']),
            'is_blind_spot': False
        }


def classify_knowledge_boundaries(text: str) -> Dict[str, Any]:
    """
    Classify whether knowledge represents AI blind spot or common sense.

    Args:
        text: Knowledge content to classify

    Returns:
        Dict with classification results:
        {
            'classification': 'blind_spot' | 'common_sense' | 'uncertain',
            'confidence': float (0.0-1.0),
            'category': str,
            'reasoning': str
        }
    """
    # Check blind spots first (higher priority)
    blind_spot_match = AIBlindSpotsTaxonomy.detect_blind_spot_category(text)
    common_sense_match = AICommonSenseTaxonomy.detect_common_sense_category(text)

    # If both match, use confidence to decide
    if blind_spot_match and common_sense_match:
        if blind_spot_match['confidence'] > common_sense_match['confidence']:
            return {
                'classification': 'blind_spot',
                'confidence': blind_spot_match['confidence'],
                'category': blind_spot_match['category'],
                'reasoning': blind_spot_match['reasoning']
            }
        else:
            return {
                'classification': 'common_sense',
                'confidence': common_sense_match['confidence'],
                'category': common_sense_match['category'],
                'reasoning': common_sense_match['reasoning']
            }

    # If only one matches
    if blind_spot_match:
        return {
            'classification': 'blind_spot',
            'confidence': blind_spot_match['confidence'],
            'category': blind_spot_match['category'],
            'reasoning': blind_spot_match['reasoning']
        }

    if common_sense_match:
        return {
            'classification': 'common_sense',
            'confidence': common_sense_match['confidence'],
            'category': common_sense_match['category'],
            'reasoning': common_sense_match['reasoning']
        }

    # Neither matched - uncertain
    return {
        'classification': 'uncertain',
        'confidence': 0.0,
        'category': 'unclassified',
        'reasoning': 'No clear match in taxonomy'
    }
