# fitz_ai/ingestion/enrichment/config.py
"""
Configuration schema for the enrichment pipeline.

Enrichment is an optional pipeline step that enhances chunks with:
1. Summaries - LLM-generated descriptions for better search (universal)
2. Artifacts - High-level project insights (type-specific plugins)
3. Hierarchy - Multi-level summaries for analytical queries (zero-config)

Config structure in .fitz/config.yaml:
    enrichment:
      enabled: true
      summary:
        enabled: false  # Opt-in: 1 LLM call per chunk
      artifacts:
        auto: true
        disabled: []
      hierarchy:
        enabled: true  # Or use: fitz ingest --hierarchy
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


@dataclass
class SummaryConfig:
    """
    Configuration for chunk-level summaries.

    Summaries are LLM-generated descriptions that improve search relevance.
    They are universal - applied to all chunk types using type-specific
    context builders for optimal results.

    WARNING: Summaries make 1 LLM call per chunk. For a codebase with 1000
    chunks, that's 1000 API calls. Enable explicitly only when needed.

    Attributes:
        enabled: Whether to generate summaries (default: False - opt-in)
        provider: LLM provider to use (defaults to config's chat provider)
        model: Model to use (defaults to config's chat model)
    """

    enabled: bool = False  # Opt-in: 1 LLM call per chunk is expensive
    provider: str | None = None
    model: str | None = None


@dataclass
class ArtifactConfig:
    """
    Configuration for project-level artifacts.

    Artifacts are high-level project summaries generated by plugins.
    Each plugin declares which content types it supports. Plugins are
    auto-discovered from the artifacts/plugins/ directory.

    Attributes:
        auto: Auto-discover and run all applicable plugins
        enabled: Explicit list of plugins to run (overrides auto)
        disabled: Plugins to skip even if applicable
    """

    auto: bool = True
    enabled: list[str] = field(default_factory=list)
    disabled: list[str] = field(default_factory=list)


@dataclass
class HierarchyRule:
    """
    A single hierarchy rule for grouping and summarizing chunks.

    Users configure rules to enable multi-level summarization of content.
    Chunks matching the path patterns are grouped by a metadata key, and
    LLM summaries are generated at group and corpus levels.

    Attributes:
        name: Unique identifier for this rule (e.g., "video_comments")
        paths: Glob patterns to filter files (e.g., ["comments/**", "*.txt"])
        group_by: Metadata key to group chunks by (e.g., "video_id")
        prompt: LLM prompt for generating group-level summaries
        corpus_prompt: Optional prompt for corpus-level summary
    """

    name: str
    paths: list[str]
    group_by: str
    prompt: str
    corpus_prompt: str | None = None


@dataclass
class HierarchyConfig:
    """
    Configuration for hierarchical enrichment.

    Hierarchical enrichment generates multi-level summaries:
    - Level 0: Original chunks (unchanged)
    - Level 1: Group summaries (chunks grouped by metadata key)
    - Level 2: Corpus summary (summary of all groups)

    Zero-config mode (recommended):
        Just set enabled=True or use `fitz ingest --hierarchy`.
        Uses smart defaults: group_by="source", default prompts.

    Power-user mode:
        Configure custom rules for complex grouping scenarios.

    Attributes:
        enabled: Whether hierarchy enrichment is active
        group_by: Metadata key for grouping (default: "source" = per-file)
        group_prompt: Custom prompt for group summaries (optional)
        corpus_prompt: Custom prompt for corpus summary (optional)
        rules: Advanced rules for power users (optional, overrides simple mode)
    """

    enabled: bool = False
    group_by: str = "source_file"  # Default: each file is a group
    group_prompt: str | None = None  # Uses DEFAULT_GROUP_PROMPT if None
    corpus_prompt: str | None = None  # Uses DEFAULT_CORPUS_PROMPT if None
    rules: list[HierarchyRule] = field(default_factory=list)  # Power user


@dataclass
class EnrichmentConfig:
    """
    Configuration for the enrichment pipeline.

    The enrichment pipeline is an optional step in document ingestion
    that enhances chunks and generates project-level insights.

    Attributes:
        enabled: Master switch for all enrichment
        summary: Chunk-level summary configuration
        artifacts: Project-level artifact configuration
        hierarchy: Hierarchical summarization configuration

    Example in .fitz/config.yaml:
        enrichment:
          enabled: true
          summary:
            enabled: true
          artifacts:
            auto: true
            disabled:
              - architecture_narrative
          hierarchy:
            enabled: true
            rules:
              - name: video_comments
                paths: ["comments/**"]
                group_by: video_id
                prompt: "Summarize sentiment and themes"
    """

    enabled: bool = False
    summary: SummaryConfig = field(default_factory=SummaryConfig)
    artifacts: ArtifactConfig = field(default_factory=ArtifactConfig)
    hierarchy: HierarchyConfig = field(default_factory=HierarchyConfig)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> "EnrichmentConfig":
        """Create config from dictionary (e.g., from YAML)."""
        if not data:
            return cls()

        summary_data = data.get("summary", {})
        artifacts_data = data.get("artifacts", {})
        hierarchy_data = data.get("hierarchy", {})

        # Parse hierarchy rules
        hierarchy_rules = []
        for rule_data in hierarchy_data.get("rules", []):
            hierarchy_rules.append(
                HierarchyRule(
                    name=rule_data.get("name", "unnamed"),
                    paths=rule_data.get("paths", []),
                    group_by=rule_data.get("group_by", ""),
                    prompt=rule_data.get("prompt", "Summarize this group."),
                    corpus_prompt=rule_data.get("corpus_prompt"),
                )
            )

        return cls(
            enabled=data.get("enabled", False),
            summary=SummaryConfig(
                enabled=summary_data.get("enabled", False),  # Opt-in
                provider=summary_data.get("provider"),
                model=summary_data.get("model"),
            ),
            artifacts=ArtifactConfig(
                auto=artifacts_data.get("auto", True),
                enabled=artifacts_data.get("enabled", []),
                disabled=artifacts_data.get("disabled", []),
            ),
            hierarchy=HierarchyConfig(
                enabled=hierarchy_data.get("enabled", False),
                group_by=hierarchy_data.get("group_by", "source_file"),
                group_prompt=hierarchy_data.get("group_prompt"),
                corpus_prompt=hierarchy_data.get("corpus_prompt"),
                rules=hierarchy_rules,
            ),
        )

    def to_dict(self) -> dict[str, Any]:
        """Convert to dictionary for serialization."""
        return {
            "enabled": self.enabled,
            "summary": {
                "enabled": self.summary.enabled,
                "provider": self.summary.provider,
                "model": self.summary.model,
            },
            "artifacts": {
                "auto": self.artifacts.auto,
                "enabled": self.artifacts.enabled,
                "disabled": self.artifacts.disabled,
            },
            "hierarchy": {
                "enabled": self.hierarchy.enabled,
                "group_by": self.hierarchy.group_by,
                "group_prompt": self.hierarchy.group_prompt,
                "corpus_prompt": self.hierarchy.corpus_prompt,
                "rules": [
                    {
                        "name": rule.name,
                        "paths": rule.paths,
                        "group_by": rule.group_by,
                        "prompt": rule.prompt,
                        "corpus_prompt": rule.corpus_prompt,
                    }
                    for rule in self.hierarchy.rules
                ],
            },
        }


__all__ = [
    "EnrichmentConfig",
    "SummaryConfig",
    "ArtifactConfig",
    "HierarchyConfig",
    "HierarchyRule",
]
