"""
Knowledge templates for Squad AI Compound Interest System.

Provides standardized templates for 6 knowledge types:
- Skills: Reusable specialized capabilities
- Rules: Execution rules and constraints
- Patterns: Code patterns and best practices
- Domain: Domain knowledge and architecture decisions
- User: User preferences and taste
- Lessons: Error lessons and anti-patterns
"""

from datetime import datetime
from typing import Dict, Any, Optional, List


class KnowledgeTemplate:
    """Base class for all knowledge templates."""

    def __init__(
        self,
        title: str,
        content: str,
        tags: Optional[List[str]] = None,
        keywords: Optional[List[str]] = None,
        source: str = "manual"
    ):
        """
        Initialize a knowledge template.

        Args:
            title: Brief title for the knowledge item
            content: Markdown content
            tags: List of tags for categorization
            keywords: List of keywords for search
            source: Source of knowledge (conversation, manual, import)
        """
        self.title = title
        self.content = content
        self.tags = tags or []
        self.keywords = keywords or []
        self.source = source

        # Will be set by subclasses
        self.knowledge_type: str = ""
        self.id_prefix: str = "kn"

    def to_dict(self) -> tuple[Dict[str, Any], str]:
        """
        Convert template to frontmatter and content.

        Returns:
            tuple[Dict[str, Any], str]: (frontmatter, content)
        """
        from .file_utils import generate_id

        now = datetime.now().isoformat()

        frontmatter = {
            'id': generate_id(self.id_prefix),
            'type': self.knowledge_type,
            'title': self.title,
            'created': now,
            'updated': now,
            'score': 0.0,
            'factors': {
                'reusability': 0.0,
                'importance': 0.0,
                'novelty': 0.0,
                'accuracy': 0.0,
                'frequency': 0.0
            },
            'tags': self.tags,
            'keywords': self.keywords,
            'source': self.source
        }

        return frontmatter, self.content


class SkillTemplate(KnowledgeTemplate):
    """Template for reusable specialized capabilities."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.knowledge_type = "skill"
        self.id_prefix = "sk"


class RuleTemplate(KnowledgeTemplate):
    """Template for execution rules and constraints."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.knowledge_type = "rule"
        self.id_prefix = "rl"


class PatternTemplate(KnowledgeTemplate):
    """Template for code patterns and best practices."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.knowledge_type = "pattern"
        self.id_prefix = "pt"


class DomainTemplate(KnowledgeTemplate):
    """Template for domain knowledge and architecture decisions."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.knowledge_type = "domain"
        self.id_prefix = "dm"


class UserTemplate(KnowledgeTemplate):
    """Template for user preferences and taste."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.knowledge_type = "user"
        self.id_prefix = "us"


class LessonTemplate(KnowledgeTemplate):
    """Template for error lessons and anti-patterns."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.knowledge_type = "lesson"
        self.id_prefix = "ls"


def create_template(
    knowledge_type: str,
    **kwargs
) -> KnowledgeTemplate:
    """
    Factory function to create a knowledge template.

    Args:
        knowledge_type: Type of knowledge (skill, rule, pattern, domain, user, lesson)
        **kwargs: Arguments to pass to template constructor

    Returns:
        KnowledgeTemplate: Appropriate template instance

    Raises:
        ValueError: If knowledge_type is invalid
    """
    templates = {
        'skill': SkillTemplate,
        'rule': RuleTemplate,
        'pattern': PatternTemplate,
        'domain': DomainTemplate,
        'user': UserTemplate,
        'lesson': LessonTemplate
    }

    template_class = templates.get(knowledge_type)

    if template_class is None:
        raise ValueError(
            f"Invalid knowledge type: {knowledge_type}. "
            f"Valid types: {list(templates.keys())}"
        )

    return template_class(**kwargs)


def get_example_content(knowledge_type: str) -> str:
    """
    Get example content for a knowledge type.

    Args:
        knowledge_type: Type of knowledge

    Returns:
        str: Example markdown content
    """
    examples = {
        'skill': """## Skill Description
Brief description of what this skill does.

## Usage
How to invoke or use this skill.

## Examples
- Example 1
- Example 2

## Notes
Additional context or considerations.""",

        'rule': """## Rule Description
What this rule enforces or constrains.

## Conditions
When this rule applies.

## Actions
What to do when rule is triggered.

## Exceptions
Edge cases or exceptions to this rule.""",

        'pattern': """## Pattern Overview
What problem this pattern solves.

## Implementation
```language
code example
```

## Best Practices
- Guideline 1
- Guideline 2

## Anti-Patterns
What to avoid.""",

        'domain': """## Domain Context
Background and context for this knowledge.

## Key Concepts
- Concept 1: Explanation
- Concept 2: Explanation

## Architecture
How this fits into the system.

## References
Links or sources.""",

        'user': """## Preference Description
What user preference this captures.

## Context
When this preference applies.

## Examples
- Example 1
- Example 2

## Priority
How important this preference is.""",

        'lesson': """## Error Description
What went wrong and why.

## Root Cause
Underlying reason for the error.

## Solution
How it was fixed.

## Prevention
How to avoid this in the future.

## Related Issues
Similar problems or patterns."""
    }

    return examples.get(knowledge_type, "## Content\nAdd your content here.")
