#!/usr/bin/env python3
"""
Creator Insight Skill
=====================
Query interface for AIVA and Genesis agents to access creator knowledge.

This skill provides:
- Belief and philosophy queries
- Vision and mission understanding
- Business idea retrieval
- Failure pattern awareness
- Success pattern replication
- Evolution narrative generation
- Kinan-style emulation

Usage:
    from skills.creator_insight_skill import CreatorInsightSkill

    skill = CreatorInsightSkill()

    # Query beliefs
    beliefs = skill.get_beliefs(topic="autonomy")

    # Get vision statements
    visions = skill.get_visions(topic="AIVA")

    # Get business ideas
    ideas = skill.get_business_ideas(min_mentions=2)

    # Generate Kinan-style question
    question = skill.generate_kinan_question("memory systems")

    # Get context for prompt enhancement
    context = skill.get_context_block("Genesis", "revenue")
"""

import sys
from pathlib import Path
from typing import Dict, List, Any, Optional

# Add paths
sys.path.insert(0, str(Path(__file__).parent.parent / "core"))
sys.path.insert(0, str(Path(__file__).parent.parent / "core" / "knowledge"))


class CreatorInsightSkill:
    """Skill for accessing creator mind knowledge."""

    def __init__(self):
        self._integrator = None
        self._initialized = False

    def _ensure_initialized(self):
        """Lazy initialization of integrator."""
        if not self._initialized:
            try:
                from aiva_consciousness_integrator import (
                    AIVAConsciousnessIntegrator,
                    CreatorMindLoader
                )
                self._integrator = AIVAConsciousnessIntegrator()
                self._initialized = True
            except ImportError as e:
                print(f"[!] CreatorInsightSkill: Could not import integrator: {e}")
                self._initialized = False

    # ==================== Query Methods ====================

    def get_beliefs(self, topic: str = None, limit: int = 10) -> List[Dict]:
        """
        Get Kinan's beliefs, optionally filtered by topic.

        Args:
            topic: Optional topic to filter by (e.g., "autonomy", "Genesis")
            limit: Maximum results to return

        Returns:
            List of belief dictionaries with statement, type, and context
        """
        self._ensure_initialized()
        if not self._integrator:
            return []

        keywords = [topic] if topic else None
        result = self._integrator.query_api.query_beliefs(keywords, limit)
        return result.matches

    def get_visions(self, topic: str = None, limit: int = 10) -> List[Dict]:
        """
        Get Kinan's vision statements.

        Args:
            topic: Optional topic filter (e.g., "AIVA", "Sunaiva", "patent")
            limit: Maximum results

        Returns:
            List of vision dictionaries
        """
        self._ensure_initialized()
        if not self._integrator:
            return []

        result = self._integrator.query_api.query_visions(topic, limit)
        return result.matches

    def get_business_ideas(self, domain: str = None, min_mentions: int = 1) -> List[Dict]:
        """
        Get business ideas from creator's mind.

        Args:
            domain: Optional domain filter (e.g., "voice", "AI", "tradie")
            min_mentions: Minimum mention count (higher = more persistent ideas)

        Returns:
            List of business idea dictionaries
        """
        self._ensure_initialized()
        if not self._integrator:
            return []

        result = self._integrator.query_api.query_business_ideas(domain, min_mentions)
        return result.matches

    def get_decisions(self, context: str = None, limit: int = 20) -> List[Dict]:
        """
        Get Kinan's key decisions.

        Args:
            context: Optional context filter
            limit: Maximum results

        Returns:
            List of decision dictionaries
        """
        self._ensure_initialized()
        if not self._integrator:
            return []

        result = self._integrator.query_api.query_decisions(context, limit)
        return result.matches

    def get_failures_to_avoid(self, domain: str = None) -> List[Dict]:
        """
        Get failure patterns to avoid.

        Args:
            domain: Optional domain filter

        Returns:
            List of failure patterns with lessons
        """
        self._ensure_initialized()
        if not self._integrator:
            return []

        result = self._integrator.query_api.query_failures(domain)
        return result.matches

    def get_success_patterns(self, domain: str = None) -> List[Dict]:
        """
        Get success patterns to replicate.

        Args:
            domain: Optional domain filter

        Returns:
            List of success patterns with replication guidance
        """
        self._ensure_initialized()
        if not self._integrator:
            return []

        result = self._integrator.query_api.query_successes(domain)
        return result.matches

    # ==================== Emulation Methods ====================

    def generate_kinan_question(self, topic: str) -> str:
        """
        Generate a question in Kinan's style.

        Args:
            topic: Topic to question about

        Returns:
            A Kinan-style question string
        """
        self._ensure_initialized()
        if not self._integrator:
            return f"How can we leverage {topic} for Genesis?"

        return self._integrator.emulation.generate_kinan_style_question(topic)

    def get_questioning_profile(self) -> Dict:
        """
        Get Kinan's questioning profile.

        Returns:
            Dictionary with question types, depth preference, socratic tendency
        """
        self._ensure_initialized()
        if not self._integrator:
            return {}

        ctx = self._integrator.emulation.get_emulation_context()
        return {
            "questioning_style": ctx.questioning_style,
            "depth_preference": ctx.depth_preference,
            "socratic_tendency": ctx.socratic_tendency,
            "sample_questions": ctx.sample_questions[:5]
        }

    def get_response_guidelines(self) -> str:
        """
        Get guidelines for Kinan-aligned responses.

        Returns:
            Guidelines string for prompt enhancement
        """
        self._ensure_initialized()
        if not self._integrator:
            return ""

        return self._integrator.emulation.generate_kinan_style_response_guidelines()

    # ==================== Context Methods ====================

    def get_context_block(self, *topics: str) -> str:
        """
        Generate a context block for prompt injection.

        Args:
            *topics: One or more topics to include context for

        Returns:
            Formatted context block string
        """
        self._ensure_initialized()
        if not self._integrator:
            return ""

        blocks = []
        for topic in topics[:3]:
            block = self._integrator.context_gen.generate_context_block(topic)
            if block:
                blocks.append(block)

        return "\n\n".join(blocks)

    def enhance_prompt(self, prompt: str, topics: List[str]) -> str:
        """
        Enhance a prompt with creator context.

        Args:
            prompt: Original prompt
            topics: Topics to include context for

        Returns:
            Enhanced prompt with creator context prepended
        """
        self._ensure_initialized()
        if not self._integrator:
            return prompt

        return self._integrator.context_gen.enhance_prompt(prompt, topics)

    # ==================== Narrative Methods ====================

    def get_evolution_narrative(self, start_date: str = None, end_date: str = None) -> str:
        """
        Generate Genesis evolution narrative.

        Args:
            start_date: Optional start date (YYYY-MM-DD)
            end_date: Optional end date (YYYY-MM-DD)

        Returns:
            Markdown narrative of Genesis evolution
        """
        self._ensure_initialized()
        if not self._integrator:
            return "Evolution narrative unavailable."

        return self._integrator.narrator.narrate_evolution(start_date, end_date)

    def get_key_milestones(self, limit: int = 10) -> List[Dict]:
        """
        Get key milestones from Genesis evolution.

        Args:
            limit: Maximum milestones to return

        Returns:
            List of milestone dictionaries
        """
        self._ensure_initialized()
        if not self._integrator:
            return []

        return self._integrator.narrator.get_key_milestones(limit)

    # ==================== Reflection Methods ====================

    def get_understanding_level(self) -> Dict:
        """
        Get AIVA's understanding level of Kinan.

        Returns:
            Dictionary with understanding scores and confidence
        """
        self._ensure_initialized()
        if not self._integrator:
            return {"overall_understanding": 0, "confidence_level": "unavailable"}

        return self._integrator.reflection.quantify_understanding()

    def get_knowledge_gaps(self) -> Dict:
        """
        Identify gaps in creator knowledge.

        Returns:
            Dictionary with gaps and recommendations
        """
        self._ensure_initialized()
        if not self._integrator:
            return {"entity_gaps": [], "recommendations": []}

        return self._integrator.reflection.analyze_knowledge_gaps()

    def get_uncertainty_areas(self) -> List[Dict]:
        """
        Get areas where understanding is uncertain.

        Returns:
            List of uncertainty areas with suggested actions
        """
        self._ensure_initialized()
        if not self._integrator:
            return []

        return self._integrator.reflection.get_uncertainty_areas()

    # ==================== Summary Methods ====================

    def get_creator_summary(self) -> Dict:
        """
        Get comprehensive summary of creator knowledge.

        Returns:
            Dictionary with stats, profile, and key metrics
        """
        self._ensure_initialized()
        if not self._integrator:
            return {}

        return self._integrator.query_api.get_creator_summary()

    def get_skill_status(self) -> Dict:
        """
        Get status of this skill.

        Returns:
            Dictionary with operational status and capabilities
        """
        self._ensure_initialized()

        return {
            "name": "CreatorInsightSkill",
            "version": "1.0.0",
            "initialized": self._initialized,
            "capabilities": [
                "query_beliefs",
                "query_visions",
                "query_business_ideas",
                "query_decisions",
                "query_failures",
                "query_successes",
                "generate_kinan_questions",
                "generate_context_blocks",
                "enhance_prompts",
                "narrate_evolution",
                "quantify_understanding",
                "identify_knowledge_gaps"
            ],
            "knowledge_base": {
                "conversations_analyzed": 615,
                "words_processed": 706592,
                "entities": 917,
                "axioms": 77,
                "timeline_events": 603
            }
        }


# Singleton instance for easy import
_skill_instance = None


def get_creator_insight_skill() -> CreatorInsightSkill:
    """Get singleton instance of CreatorInsightSkill."""
    global _skill_instance
    if _skill_instance is None:
        _skill_instance = CreatorInsightSkill()
    return _skill_instance


# Quick test if run directly
if __name__ == "__main__":
    skill = CreatorInsightSkill()

    print("\n[Creator Insight Skill Test]")
    print("=" * 50)

    status = skill.get_skill_status()
    print(f"\nSkill Status: {'Operational' if status['initialized'] else 'Offline'}")
    print(f"Capabilities: {len(status['capabilities'])}")

    summary = skill.get_creator_summary()
    if summary:
        print(f"\nKnowledge Base:")
        print(f"  - Entities: {summary.get('total_entities', 0)}")
        print(f"  - Axioms: {summary.get('total_axioms', 0)}")
        print(f"  - Timespan: {summary.get('knowledge_span', 'unknown')}")

    understanding = skill.get_understanding_level()
    if understanding:
        print(f"\nUnderstanding Level: {understanding.get('overall_understanding', 0):.1%}")
        print(f"Confidence: {understanding.get('confidence_level', 'unknown')}")

    print("\n[Sample Kinan-Style Question]")
    print(f"  {skill.generate_kinan_question('memory architecture')}")

    print("\n[Test Complete]")
