#!/usr/bin/env python3
"""
Database Initialization Script.

This script initializes all database tables in Appwrite.
Run this script once to set up the database schema before running the application.

Usage:
    python scripts/init_database.py
"""

import sys
import os
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from dotenv import load_dotenv
from app.services.database_init import init_database
from app.utils.logging import get_logger

# Load environment variables
load_dotenv()

logger = get_logger(__file__)


def main():
    """Initialize database tables."""
    print("=" * 60)
    print("Code of Conquest - Database Initialization")
    print("=" * 60)
    print()

    # Verify environment variables are set
    required_vars = [
        'APPWRITE_ENDPOINT',
        'APPWRITE_PROJECT_ID',
        'APPWRITE_API_KEY',
        'APPWRITE_DATABASE_ID'
    ]

    missing_vars = [var for var in required_vars if not os.getenv(var)]
    if missing_vars:
        print("❌ ERROR: Missing required environment variables:")
        for var in missing_vars:
            print(f"   - {var}")
        print()
        print("Please ensure your .env file is configured correctly.")
        sys.exit(1)

    print("✓ Environment variables loaded")
    print(f"  Endpoint: {os.getenv('APPWRITE_ENDPOINT')}")
    print(f"  Project: {os.getenv('APPWRITE_PROJECT_ID')}")
    print(f"  Database: {os.getenv('APPWRITE_DATABASE_ID')}")
    print()

    # Initialize database
    print("Initializing database tables...")
    print()

    try:
        results = init_database()

        print()
        print("=" * 60)
        print("Initialization Results")
        print("=" * 60)
        print()

        success_count = 0
        failed_count = 0

        for table_name, success in results.items():
            if success:
                print(f"✓ {table_name}: SUCCESS")
                success_count += 1
            else:
                print(f"✗ {table_name}: FAILED")
                failed_count += 1

        print()
        print(f"Total: {success_count} succeeded, {failed_count} failed")
        print()

        if failed_count > 0:
            print("⚠️  Some tables failed to initialize. Check logs for details.")
            sys.exit(1)
        else:
            print("✓ All tables initialized successfully!")
            print()
            print("You can now start the application.")

    except Exception as e:
        logger.error("Database initialization failed", error=str(e))
        print()
        print(f"❌ ERROR: {str(e)}")
        print()
        print("Check logs for details.")
        sys.exit(1)


if __name__ == '__main__':
    main()
