#!/usr/bin/env python3
"""
Genesis Skill Factory v1.0
===========================
The "Procreation" module of Genesis. 
Converts Strategic Axioms and Knowledge Items into executable Python Skills.
"""

import os
import sys
import json
import re
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional

# Add core to path
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

try:
    from genesis_heartbeat import Axiom
except ImportError:
    # Minimal stub
    class Axiom:
        def __init__(self, **kwargs): self.__dict__.update(kwargs)

class SkillFactory:
    def __init__(self, workspace: str = "E:/genesis-system"):
        self.workspace = Path(workspace)
        self.skills_dir = self.workspace / "skills"
        self.axioms_path = self.workspace / "data" / "axioms.json"
        
        self.skills_dir.mkdir(exist_ok=True)
        
    def generate_skill_from_axiom(self, axiom: Dict) -> Optional[str]:
        """
        Takes an axiom and generates a skill file.
        In a production environment, this would call an LLM to write the code.
        For this 'go' demonstration, we use a template-based approach with 
        dynamic metadata injection.
        """
        statement = axiom.get("statement", "Generic Skill")
        domain = axiom.get("domain", "general")
        axiom_id = axiom.get("axiom_id", "unknown")
        
        # Create a safe filename
        skill_name = re.sub(r'[^a-zA-Z0-9]', '_', statement.lower())[:40].strip('_')
        if not skill_name:
            skill_name = f"skill_{axiom_id}"
            
        file_path = self.skills_dir / f"{skill_name}.py"
        
        print(f"🛠️  Factory: Generating skill '{skill_name}' from axiom {axiom_id}...")
        
        template = f'''#!/usr/bin/env python3
"""
Genesis Generated Skill: {skill_name}
=======================================
Derived from Axiom: {statement}
Domain: {domain}
Axiom ID: {axiom_id}
Generated: {datetime.now().isoformat()}
"""

import os
import sys
from pathlib import Path
from typing import Dict, Any

# Add core to path
sys.path.append(str(Path(__file__).parent.parent / "core"))

try:
    from blackboard import Blackboard, EntryType
except ImportError:
    class Blackboard:
        def write(self, **kwargs): print(f"BB WRITE: {{kwargs}}")
    class EntryType:
        SKILL_EXECUTION = "skill_execution"

class {skill_name.title().replace("_", "")}Skill:
    """
    Autonomous skill generated by the Genesis Evolution Engine.
    Objective: Implement learning from axiom "{statement}"
    """
    def __init__(self):
        self.bb = Blackboard()
        self.skill_name = "{skill_name}"
        
    def execute(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """
        Executes the logic associated with this skill.
        """
        print(f"[SKILL] Executing {{self.skill_name}} with params: {{params}}")
        
        # Log to blackboard
        self.bb.write(
            entry_type="skill_execution",
            content={{
                "skill": self.skill_name,
                "axiom_id": "{axiom_id}",
                "params": params,
                "status": "success",
                "result": "Autonomous capability activated based on learned axiom."
            }},
            author="skill_factory",
            tags=["evolved_skill", "{domain}"]
        )
        
        return {{
            "status": "completed",
            "skill": self.skill_name,
            "message": f"Successfully applied axiom: {statement}"
        }}

if __name__ == "__main__":
    skill = {skill_name.title().replace("_", "")}Skill()
    result = skill.execute({{"mode": "test"}})
    print(f"[DONE] {{result}}")
'''
        
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(template)
            
        return str(file_path)

    def run_factory(self):
        """Processes recent axioms and generates new skills."""
        if not self.axioms_path.exists():
            print("⚠️  No axioms found. Run heartbeat or evolution first.")
            return
            
        with open(self.axioms_path, "r", encoding="utf-8") as f:
            data = json.load(f)
            
        axioms = data.get("axioms", {})
        if not axioms:
            print("⚠️  Axiom list is empty.")
            return
            
        print(f"🏭  Skill Factory: Processing {len(axioms)} axioms...")
        for aid, adict in axioms.items():
            # Only create skill if it doesn't exist
            # (In a real system, we'd check if the skill is already 'mastered')
            self.generate_skill_from_axiom(adict)

if __name__ == "__main__":
    factory = SkillFactory()
    factory.run_factory()
