#!/usr/bin/env python3
"""
GENESIS SKILL CRYSTALLIZER
==========================
Implementation of Autonomous Skill Acquisition.
Transforms technical intelligence into executable Python skills.
"""

import json
import logging
import os
from pathlib import Path
from typing import Dict, List, Any, Optional

# Add genesis root to path
import sys
GENESIS_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(GENESIS_ROOT))

class SkillCrystallizer:
    """
    Automates the creation of new Genesis skills based on extracted technical patterns.
    """
    
    def __init__(self, skills_dir: Optional[Path] = None):
        self.skills_dir = skills_dir or GENESIS_ROOT / "skills"
        self.skills_dir.mkdir(parents=True, exist_ok=True)
        from core.gemini_executor import GeminiExecutor
        self.executor = GeminiExecutor(use_rate_maximizer=True)

    def crystallize_skill(self, intelligence: Dict[str, Any], skill_name: str) -> Optional[Path]:
        """
        Generates a Python skill file from technical intelligence.
        """
        logging.info(f"Crystallizing skill: {skill_name}")
        
        prompt = f"""
        # GENESIS SKILL CRYSTALLIZATION
        
        Based on the following technical intelligence, generate a PRODUCTION-READY Python skill for the Genesis System.
        
        INTELLIGENCE:
        {json.dumps(intelligence, indent=2)}
        
        SKILL NAME: {skill_name}
        
        REQUIREMENTS:
        1. Class name must be `{skill_name.replace('_', ' ').title().replace(' ', '')}Skill`.
        2. Must include an `execute` method.
        3. Must be self-contained and use `core` utilities.
        4. Include docstrings explaining the technical pattern this skill follows.
        5. Tone: "Nick Ponte / Julian Goldie" - result-oriented, technical but business-aligned.
        
        Return ONLY the Python code in a code block.
        """
        
        response = self.executor.execute_optimized(
            prompt=prompt,
            task_type="code_generation",
            max_tokens=8192
        )
        
        if response.success:
            code = self._extract_code(response.response)
            file_path = self.skills_dir / f"{skill_name.lower()}.py"
            file_path.write_text(code)
            logging.info(f"Skill crystallized at {file_path}")
            return file_path
            
        return None

    def _extract_code(self, response: str) -> str:
        if "```python" in response:
            return response.split("```python")[1].split("```")[0].strip()
        elif "```" in response:
            return response.split("```")[1].split("```")[0].strip()
        return response.strip()

if __name__ == "__main__":
    # Test
    crystallizer = SkillCrystallizer()
    intel = {
        "technical_specs": ["YouTube API", "Python"],
        "implementation_patterns": ["Fetch transcripts", "Extract keywords"],
        "axioms": ["Information is the new oil"]
    }
    crystallizer.crystallize_skill(intel, "youtube_keyword_extractor")
