#!/usr/bin/env python3
"""
TITAN QUICK LAUNCH - Streamlined cache creation with critical files only.
"""

import os
import sys
import time
import warnings
from pathlib import Path
from datetime import timedelta

warnings.filterwarnings('ignore')

# Add genesis root
GENESIS_ROOT = Path(__file__).parent.parent.parent
sys.path.insert(0, str(GENESIS_ROOT))

# API key
API_KEY = os.environ.get('GEMINI_API_KEY', 'AIzaSyCT_rx0NusUJWoqtT7uxHAKEfHo129SJb8')
os.environ['GEMINI_API_KEY'] = API_KEY

import google.generativeai as genai
genai.configure(api_key=API_KEY)

def get_critical_files() -> list:
    """Get most critical files for caching (< 100 files)."""
    critical_dirs = [
        GENESIS_ROOT / "core",
    ]

    files = []
    for d in critical_dirs:
        if d.exists():
            # Get top-level .py files only (no recursion for speed)
            for f in d.glob("*.py"):
                if f.stat().st_size < 100_000:  # Max 100KB per file
                    files.append(f)

    # Add key skill files
    skill_dir = GENESIS_ROOT / "skills"
    if skill_dir.exists():
        for f in skill_dir.glob("*.py"):
            if f.stat().st_size < 100_000:
                files.append(f)

    # Limit to 50 files max for quick launch
    files = sorted(files, key=lambda f: f.stat().st_size, reverse=True)[:50]
    return files

def create_text_content(files: list) -> str:
    """Concatenate files into single text content."""
    content_parts = []

    for f in files:
        try:
            text = f.read_text(encoding='utf-8', errors='ignore')
            content_parts.append(f"### FILE: {f.relative_to(GENESIS_ROOT)} ###\n{text}\n")
        except:
            pass

    return "\n\n".join(content_parts)

def main():
    print("=" * 60)
    print("TITAN QUICK LAUNCH - Critical Files Cache")
    print("=" * 60)

    # Get files
    print("\n[1] Collecting critical files...")
    files = get_critical_files()
    print(f"    Selected {len(files)} files")

    # Concatenate content
    print("\n[2] Preparing content...")
    content = create_text_content(files)
    total_chars = len(content)
    estimated_tokens = total_chars // 4
    print(f"    Total characters: {total_chars:,}")
    print(f"    Estimated tokens: {estimated_tokens:,}")

    # Create cache using inline content (faster than file upload)
    print("\n[3] Creating Titan cache...")
    start = time.time()

    try:
        cache = genai.caching.CachedContent.create(
            model="gemini-2.0-flash-001",
            display_name=f"genesis_quick_{int(time.time())}",
            system_instruction="""You are the Genesis Titan Intelligence with knowledge of the Genesis codebase.
Answer questions about code, architecture, and implementation details based on the cached files.""",
            contents=[content],
            ttl=timedelta(minutes=60),
        )

        elapsed = time.time() - start
        print(f"    SUCCESS in {elapsed:.1f}s!")
        print(f"    Cache name: {cache.name}")
        print(f"    Tokens: {cache.usage_metadata.total_token_count:,}")
        print(f"    Expires: {cache.expire_time}")

        # Test query
        print("\n[4] Testing with query...")
        model = genai.GenerativeModel.from_cached_content(cache)
        response = model.generate_content("What are the main Python files in the core/ directory and what do they do? List 5 key ones.")

        print(f"\n    Response:\n{response.text[:500]}...")

        print("\n" + "=" * 60)
        print("TITAN CACHE READY!")
        print(f"Cache Name: {cache.name}")
        print("=" * 60)

        return cache.name

    except Exception as e:
        print(f"    FAILED: {e}")
        return None

if __name__ == '__main__':
    main()
