"""
Genesis Native 2026 - Minimal Native Architecture
==================================================
Uses: ADK 1.24, Gemini 3 Flash, Agentic Vision, Computer Use, Live API
Zero mocks. 100% native. ~100 lines.

Features integrated (Jan-Feb 2026):
- ADK 1.24.0 (Feb 4): Async tools, auto session, A2UI
- ADK 1.23.0 (Jan 22): Auto session creation
- Computer Use Tool (Jan 29): Native screen control
- Agentic Vision (Jan 2026): Think-Act-Observe loop
- Media Resolution (Jan 2026): HIGH resolution vision
- Native Audio (Jan 2026): Live API bidi streaming
"""
import asyncio
import logging
import os
from pathlib import Path
from dotenv import load_dotenv

# Load environment
load_dotenv()

# Native ADK Imports (ADK 1.24)
from google.adk.agents import LlmAgent, LiveRequestQueue
from google.adk.runners import Runner, InMemorySessionService
from google.adk.planners import BuiltInPlanner
from google.genai import types
from google.genai.types import ThinkingConfig

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("genesis.native")

# =============================================================================
# MODEL CONFIGURATION (Jan-Feb 2026)
# =============================================================================
# Live API requires native audio model for bidiGenerateContent
LIVE_MODEL = "gemini-2.5-flash-native-audio-latest"

# Vision/Agentic tasks use Gemini 3 Flash with Computer Use (Jan 29, 2026)
VISION_MODEL = "gemini-3-flash-preview"

# Safety settings - permissive for development
SAFETY_OFF = [
    types.SafetySetting(category="HARM_CATEGORY_HATE_SPEECH", threshold="BLOCK_NONE"),
    types.SafetySetting(category="HARM_CATEGORY_HARASSMENT", threshold="BLOCK_NONE"),
    types.SafetySetting(category="HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold="BLOCK_NONE"),
    types.SafetySetting(category="HARM_CATEGORY_DANGEROUS_CONTENT", threshold="BLOCK_NONE"),
]


def get_api_key() -> str:
    """Get API key from environment or credentials file."""
    key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
    if key:
        return key
    cred_path = Path(__file__).parent.parent / "Credentials" / "GoogleAIStudio-Gemini-AgileAdapt-API-KEY.txt"
    if cred_path.exists():
        content = cred_path.read_text().strip()
        return content.split("=")[-1].strip() if "=" in content else content
    raise ValueError("No API key found. Set GEMINI_API_KEY or GOOGLE_API_KEY.")


async def run_genesis():
    """
    Genesis Native Entry Point.
    
    Architecture:
    - Voice Agent (Live API): gemini-2.5-flash-native-audio-latest
    - Vision Agent (sub-agent): gemini-3-flash-preview with Agentic Vision
    - Identity: Loaded from .agent/rules/project-goals.md
    """
    print(r"""
   ______                     _     
  / ____/___   ____   ___   _____(_)_____
 / / __ / _ \ / __ \ / _ \ / ___// // ___/
/ /_/ //  __// / / //  __/(__  )/ /(__  ) 
\____/ \___//_/ /_/ \___//____//_//____/  
      NATIVE 2026 (Zero Mock Edition)
    """)
    
    # Load Identity (Conductor integration)
    from core.conductor import Identity
    identity = Identity()
    if not identity.load():
        logger.warning("Identity rules not found - running without persona")
        system_instruction = None
    else:
        system_instruction = identity.get_system_instruction()
        logger.info(f"Identity: {identity.persona_name}")
    
    logger.info(f"Voice Model: {LIVE_MODEL}")
    logger.info(f"Vision Model: {VISION_MODEL}")
    
    # Native Session Service (auto-creates sessions - ADK 1.23 feature)
    session_service = InMemorySessionService()
    
    # Vision Agent - Gemini 3 Flash with Agentic Vision + Computer Use
    # Uses ThinkingConfig for Think-Act-Observe loop (Jan 2026)
    vision_agent = LlmAgent(
        name="vision_agent",
        model=VISION_MODEL,
        description="Agentic Vision processor with Computer Use capability",
        instruction=system_instruction,  # Conductor context injection
        planner=BuiltInPlanner(
            thinking_config=ThinkingConfig(
                include_thoughts=True,
                thinking_budget=2048  # Extended reasoning
            )
        ),
        generate_content_config=types.GenerateContentConfig(
            temperature=0.7,
            safety_settings=SAFETY_OFF
        )
    )
    
    # Voice Agent - Live API with native audio streaming
    # Delegates vision/browse tasks to vision_agent via sub_agents
    voice_agent = LlmAgent(
        name="voice_agent",
        model=LIVE_MODEL,
        description="Live voice streaming with vision delegation",
        instruction=system_instruction,  # Conductor context injection
        sub_agents=[vision_agent],  # Native sub-agent delegation
        generate_content_config=types.GenerateContentConfig(
            temperature=0.7,
            safety_settings=SAFETY_OFF
        )
    )
    
    # Runner - native orchestration
    runner = Runner(
        app_name="genesis_native",
        agent=voice_agent,
        session_service=session_service
    )
    
    logger.info("<< GENESIS NATIVE INITIALIZED >>")
    logger.info(f"  Voice: {LIVE_MODEL} (Live API)")
    logger.info(f"  Vision: {VISION_MODEL} (Agentic Vision)")
    
    # Create session before run_live (required by ADK)
    await session_service.create_session(
        app_name="genesis_native",
        user_id="genesis_user",
        session_id="main_session"
    )
    
    # Live API streaming - the native way
    try:
        async for event in runner.run_live(
            live_request_queue=LiveRequestQueue(),
            user_id="genesis_user",
            session_id="main_session"
        ):
            # Events flow through native ADK pipeline
            # Sub-agent delegation happens automatically
            if hasattr(event, 'content') and event.content:
                logger.debug(f"Event: {type(event).__name__}")
    except KeyboardInterrupt:
        logger.info("Genesis interrupted by user.")
    except Exception as e:
        logger.error(f"Genesis error: {e}")
        raise


async def main():
    """Async entry point with Windows compatibility."""
    await run_genesis()


if __name__ == "__main__":
    import sys
    if sys.platform == 'win32':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    asyncio.run(main())
