#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
DATABASE SETUP SCRIPT - INDEX-SISTEM-JOCURI

Script pentru recrearea bazelor de date din .gitignore
Folosește clasele DatabaseManager pentru consistență

Usage:
    python scripts/create_databases.py
    python scripts/create_databases.py --clear-existing
"""

import sys
import argparse
from pathlib import Path

# Add src to path so we can import our modules
sys.path.append(str(Path(__file__).parent.parent / 'src'))

from database import DatabaseManager
from game_library_manager import GameLibraryManager

def create_main_database(db_path: str = "data/activities.db", clear: bool = False):
    """Create the main activities database"""
    db_file = Path(db_path)
    
    if clear and db_file.exists():
        print(f"🗑️  Removing existing database: {db_path}")
        db_file.unlink()
    
    print(f"📊 Creating main database: {db_path}")
    db = DatabaseManager(db_path)
    
    # Test the database
    try:
        stats = db.get_statistics()
        print(f"✅ Database created successfully: {stats['total_activities']} activities")
        return True
    except Exception as e:
        print(f"❌ Error creating database: {e}")
        return False

def create_game_library_database(db_path: str = "data/game_library.db", clear: bool = False):
    """Create the legacy game library database"""
    db_file = Path(db_path)
    
    if clear and db_file.exists():
        print(f"🗑️  Removing existing database: {db_path}")
        db_file.unlink()
    
    print(f"📊 Creating game library database: {db_path}")
    manager = GameLibraryManager(db_path)
    
    print(f"✅ Game library database created successfully")
    return True

def create_test_database(db_path: str = "data/test_activities.db", clear: bool = False):
    """Create the test database"""
    db_file = Path(db_path)
    
    if clear and db_file.exists():
        print(f"🗑️  Removing existing database: {db_path}")
        db_file.unlink()
    
    print(f"📊 Creating test database: {db_path}")
    db = DatabaseManager(db_path)
    
    # Add some test data
    test_activity = {
        'title': 'Test Activity - Setup Script',
        'description': 'This is a test activity created by the setup script',
        'file_path': 'test/sample.txt',
        'file_type': 'TXT',
        'category': 'test',
        'age_group': '8-12 ani',
        'participants': '5-10 persoane',
        'duration': '15-30min',
        'materials': 'Fără materiale',
        'tags': '["test", "setup"]',
        'source_text': 'Sample test content for verification'
    }
    
    try:
        db.insert_activity(test_activity)
        stats = db.get_statistics()
        print(f"✅ Test database created with sample data: {stats['total_activities']} activities")
        return True
    except Exception as e:
        print(f"❌ Error creating test database: {e}")
        return False

def ensure_data_directory():
    """Ensure the data directory exists"""
    data_dir = Path("data")
    if not data_dir.exists():
        print(f"📁 Creating data directory: {data_dir}")
        data_dir.mkdir(parents=True)
    else:
        print(f"📁 Data directory exists: {data_dir}")

def main():
    """Main setup function"""
    parser = argparse.ArgumentParser(description='Create databases for INDEX-SISTEM-JOCURI')
    parser.add_argument('--clear-existing', '-c', action='store_true',
                       help='Remove existing databases before creating new ones')
    parser.add_argument('--main-only', action='store_true',
                       help='Create only the main activities database')
    parser.add_argument('--test-only', action='store_true',
                       help='Create only the test database')
    
    args = parser.parse_args()
    
    print("🚀 DATABASE SETUP - INDEX-SISTEM-JOCURI")
    print("=" * 50)
    
    # Ensure data directory exists
    ensure_data_directory()
    
    success_count = 0
    total_count = 0
    
    if args.test_only:
        total_count = 1
        if create_test_database(clear=args.clear_existing):
            success_count += 1
    elif args.main_only:
        total_count = 1
        if create_main_database(clear=args.clear_existing):
            success_count += 1
    else:
        # Create all databases
        databases = [
            ("Main activities", lambda: create_main_database(clear=args.clear_existing)),
            ("Game library", lambda: create_game_library_database(clear=args.clear_existing)),
            ("Test activities", lambda: create_test_database(clear=args.clear_existing))
        ]
        
        total_count = len(databases)
        
        for name, create_func in databases:
            print(f"\n📂 Creating {name} database...")
            try:
                if create_func():
                    success_count += 1
            except Exception as e:
                print(f"❌ Failed to create {name} database: {e}")
    
    print("\n" + "=" * 50)
    print(f"🎯 SUMMARY: {success_count}/{total_count} databases created successfully")
    
    if success_count == total_count:
        print("✅ All databases ready!")
        print("\nNext steps:")
        print("1. Run indexer: cd src && python indexer.py --clear-db")
        print("2. Start web app: cd src && python app.py")
    else:
        print("⚠️  Some databases failed to create. Check errors above.")
        return 1
    
    return 0

if __name__ == '__main__':
    sys.exit(main())