"""Skill Forge - The Recursive Blacksmith.
======================================

"Iron sharpens iron, so one person sharpens another."

The Skill Forge is responsible for "crystallizing" success.
When the Universal Router successfully executes a chain multiple times,
the Emergence Engine triggers the Forge to turn that dynamic chain
into a static, optimized "Skill" (Pattern).

This is the core of Recursive Self-Improvement.
"""

import json
import logging
from dataclasses import dataclass
from pathlib import Path

from whitemagic.core.intelligence.omni.universal_router import ExecutionChain

logger = logging.getLogger(__name__)

@dataclass
class ForgedSkill:
    """A crystallized skill ready for reuse."""

    name: str
    description: str
    trigger_phrases: list[str]
    optimized_chain: ExecutionChain
    version: int = 1

class SkillForge:
    """Forges transient actions into permanent skills.
    """

    def __init__(self, skill_library_path: Path = Path("memory/skills")):
        self.skill_library_path = skill_library_path
        self.skill_library_path.mkdir(parents=True, exist_ok=True)
        self.known_skills: dict[str, ForgedSkill] = {}
        self._load_skills()

    def _load_skills(self) -> None:
        """Load all forged skills from disk."""
        count = 0
        for skill_file in self.skill_library_path.glob("*.json"):
            try:
                with open(skill_file, "r") as f:
                    data = json.load(f)

                # Reconstruct ExecutionChain
                from whitemagic.core.intelligence.omni.universal_router import GanaStep
                steps = [
                    GanaStep(
                        mansion=s["mansion"],
                        operation=s["operation"],
                        context_key=s["context"],
                        parameters={},
                    ) for s in data.get("steps", [])
                ]

                chain = ExecutionChain(
                    intent=data.get("description", ""),
                    steps=steps,
                    estimated_complexity=len(steps),
                    required_capabilities=[],
                )

                skill = ForgedSkill(
                    name=data["name"],
                    description=data["description"],
                    trigger_phrases=data["triggers"],
                    optimized_chain=chain,
                )

                self.known_skills[skill.name] = skill
                count += 1
            except Exception as e:
                logger.warning(f"Failed to load skill {skill_file}: {e}")

        if count > 0:
            logger.info(f"🧠 Skill Forge loaded {count} crystallized skills.")

    def assess_pattern(self, chain: ExecutionChain, success_metric: float) -> bool:
        """Determine if a chain is worthy of becoming a skill.
        """
        # Simple heuristic: if it's complex and successful, forge it.
        if success_metric > 0.8 and len(chain.steps) > 2:
            return True
        return False

    def forge(self, chain: ExecutionChain, name: str) -> ForgedSkill:
        """Convert a Chain into a clean, reusable Skill.
        In a full system, this would write Python code.
        """
        logger.info(f"🔨 Forging new skill: '{name}' from chain for '{chain.intent}'")

        skill = ForgedSkill(
            name=name,
            description=f"Auto-forged skill for: {chain.intent}",
            trigger_phrases=[chain.intent],
            optimized_chain=chain,
        )

        self._save_skill(skill)
        return skill

    def _save_skill(self, skill: ForgedSkill) -> None:
        """Persist the skill to disk and update the SKILLS.md registry."""
        skill_file = self.skill_library_path / f"{skill.name.lower()}.json"

        data = {
            "name": skill.name,
            "description": skill.description,
            "triggers": skill.trigger_phrases,
            "steps": [
                {
                    "mansion": s.mansion,
                    "operation": s.operation,
                    "context": s.context_key,
                }
                for s in skill.optimized_chain.steps
            ],
        }

        with open(skill_file, "w") as f:
            json.dump(data, f, indent=2)

        logger.info(f"💾 Skill saved to {skill_file}")
        self._update_skills_md()

    def _update_skills_md(self) -> None:
        """Regenerate the SKILLS.md catalog for AI consumption."""
        catalog_path = self.skill_library_path.parent / "SKILLS.md"
        catalog_path.parent.mkdir(parents=True, exist_ok=True)

        content = ["# Whitemagic Skill Registry\n",
                   "> Auto-generated by Skill Forge. DO NOT EDIT MANUALLY.\n",
                   "| Skill Name | Description | Triggers | Complexity |",
                   "| :--- | :--- | :--- | :--- |"]

        for skill in self.known_skills.values():
            triggers = ", ".join([f"`{t}`" for t in skill.trigger_phrases[:3]])
            complexity = f"{skill.optimized_chain.estimated_complexity:.1f}"
            row = f"| **{skill.name}** | {skill.description} | {triggers} | {complexity} |"
            content.append(row)

        content.append("\n\n---\n*To use a skill, reference it by name in your intent.*")

        with open(catalog_path, "w") as f:
            f.write("\n".join(content))

        logger.info(f"📘 Updated SKILLS.md registry at {catalog_path}")

# Singleton accessor
_forge = None
def get_skill_forge() -> SkillForge:
    global _forge
    if _forge is None:
        _forge = SkillForge()
    return _forge
