#!/usr/bin/env python3
"""
TITAN MEMORY LAUNCHER
=====================
Creates full-stack Titan cache and starts auto-refresh daemon.

Usage:
    python core/titan/launcher.py [--ttl MINUTES] [--no-daemon]

VERIFICATION_STAMP
Story: TITAN-004 (Launcher)
Verified By: Claude
Verified At: 2026-01-23
"""

import os
import sys
import time
import argparse
import logging
from pathlib import Path

# Add genesis root
GENESIS_ROOT = Path(__file__).parent.parent.parent
sys.path.insert(0, str(GENESIS_ROOT))

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s | %(levelname)-8s | %(message)s',
    datefmt='%H:%M:%S'
)
logger = logging.getLogger(__name__)

# Suppress verbose warnings
import warnings
warnings.filterwarnings('ignore', category=FutureWarning)


def main():
    parser = argparse.ArgumentParser(description="Titan Memory Launcher")
    parser.add_argument('--ttl', type=int, default=60, help='Cache TTL in minutes (default: 60)')
    parser.add_argument('--no-daemon', action='store_true', help='Skip starting the refresh daemon')
    parser.add_argument('--query', type=str, help='Optional query to test the cache')
    args = parser.parse_args()

    print("""
╔══════════════════════════════════════════════════════════════════╗
║              TITAN MEMORY FULL-STACK LAUNCHER                    ║
║              Genesis Codebase Context Cache                      ║
╚══════════════════════════════════════════════════════════════════╝
""")

    # Set API key
    api_key = os.environ.get('GEMINI_API_KEY', 'AIzaSyCT_rx0NusUJWoqtT7uxHAKEfHo129SJb8')
    os.environ['GEMINI_API_KEY'] = api_key

    # Step 1: File scan
    print("[1/4] Scanning codebase...")
    from core.titan.file_scanner import FileScanner

    scanner = FileScanner()
    files = scanner.scan()

    print(f"      Found {len(files)} Python files")
    print(f"      Total size: {scanner.get_total_size(files) / 1024 / 1024:.2f} MB")
    print(f"      Estimated tokens: {scanner.get_estimated_tokens(files):,}")
    print()

    # Check token limits (Gemini context cache limit is ~2M tokens for flash)
    estimated_tokens = scanner.get_estimated_tokens(files)
    if estimated_tokens > 1_500_000:
        print("      WARNING: Large token count. Using selective caching...")
        # Filter to most important directories
        scanner = FileScanner(directories=['core', 'skills', 'tools'])
        files = scanner.scan()
        print(f"      Reduced to {len(files)} files ({scanner.get_estimated_tokens(files):,} tokens)")
    print()

    # Step 2: Create cache
    print("[2/4] Creating Titan cache (this may take 1-3 minutes)...")
    from core.titan.cache_manager import TitanCacheManager

    manager = TitanCacheManager(api_key)

    start_time = time.time()
    cache = manager.create_cache(
        files=files,
        display_name=f"genesis_fullstack_{int(time.time())}",
        ttl_minutes=args.ttl,
    )
    elapsed = time.time() - start_time

    if not cache:
        print("      FAILED: Could not create cache")
        print("      Check API key and network connection")
        sys.exit(1)

    print(f"      SUCCESS: Cache created in {elapsed:.1f}s")
    print(f"      Name: {cache.name}")
    print(f"      Tokens: {cache.token_count:,}")
    print(f"      Expires: {cache.expire_time}")
    print()

    # Step 3: Start daemon
    if not args.no_daemon:
        print("[3/4] Starting auto-refresh daemon...")
        from core.titan.refresh_daemon import TitanRefreshDaemon

        daemon = TitanRefreshDaemon(manager, check_interval=60)
        daemon.start()

        print(f"      Daemon started (will refresh at {args.ttl - 10} min mark)")
        print()
    else:
        print("[3/4] Skipping daemon (--no-daemon flag)")
        print()

    # Step 4: Test query
    print("[4/4] Testing cache with query...")

    test_query = args.query or "What are the main components of the Genesis execution layer?"

    response = manager.query(test_query, cache_name=cache.name)

    if response:
        print(f"      Query: {test_query}")
        print(f"      Response preview: {response[:200]}...")
        print()
        print("      CACHE IS WORKING!")
    else:
        print("      WARNING: Query returned no response")
    print()

    # Summary
    print("""
╔══════════════════════════════════════════════════════════════════╗
║                      TITAN CACHE READY                           ║
╠══════════════════════════════════════════════════════════════════╣""")
    print(f"║  Cache Name: {cache.name:<49}║")
    print(f"║  Token Count: {cache.token_count:,} tokens{' ' * (39 - len(f'{cache.token_count:,}'))}║")
    print(f"║  TTL: {args.ttl} minutes{' ' * (52 - len(f'{args.ttl}'))}║")
    print(f"║  Auto-Refresh: {'Enabled' if not args.no_daemon else 'Disabled':<48}║")
    print("""╚══════════════════════════════════════════════════════════════════╝
""")

    # Usage instructions
    print("To query the cache from Python:")
    print("""
    from core.titan import TitanCacheManager

    manager = TitanCacheManager()
    response = manager.query("How does the RWL swarm work?")
    print(response)
""")

    if not args.no_daemon:
        print("Daemon is running in background. Press Ctrl+C to stop.")
        try:
            while True:
                time.sleep(60)
        except KeyboardInterrupt:
            print("\nShutting down...")
            daemon.stop()


if __name__ == '__main__':
    main()
