import os
import sqlite3
import uuid
from datetime import datetime

def migrate_sqlite():
    db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cloudvault_central.db")
    conn = sqlite3.connect(db_path)
    c = conn.cursor()

    def get_columns(table_name):
        c.execute(f"PRAGMA table_info({table_name})")
        return [row[1] for row in c.fetchall()]

    def table_exists(table_name):
        c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,))
        return c.fetchone() is not None

    print("Step 1: Adding missing columns to existing legacy tables...")

    # Users table
    if table_exists("users"):
        cols = get_columns("users")
        if "name" not in cols:
            c.execute("ALTER TABLE users ADD COLUMN name TEXT")
            c.execute("UPDATE users SET name = display_name WHERE name IS NULL AND display_name IS NOT NULL")
            c.execute("UPDATE users SET name = substr(email, 1, instr(email, '@') - 1) WHERE name IS NULL")
        if "account_status" not in cols:
            c.execute("ALTER TABLE users ADD COLUMN account_status TEXT DEFAULT 'active'")
        if "referral_code" not in cols:
            c.execute("ALTER TABLE users ADD COLUMN referral_code TEXT")
        if "referred_by_id" not in cols:
            c.execute("ALTER TABLE users ADD COLUMN referred_by_id TEXT")
        if "referral_count" not in cols:
            c.execute("ALTER TABLE users ADD COLUMN referral_count INTEGER DEFAULT 0")
        conn.commit()

        # Generate referral code for existing users without one
        c.execute("SELECT id, email FROM users WHERE referral_code IS NULL")
        rows = c.fetchall()
        for r_id, r_email in rows:
            prefix = "ESPACE"
            short_id = uuid.uuid4().hex[:6].upper()
            code = f"{prefix}{short_id}"
            c.execute("UPDATE users SET referral_code = ? WHERE id = ?", (code, r_id))
        conn.commit()

    # Connected accounts table
    if table_exists("connected_accounts"):
        cols = get_columns("connected_accounts")
        if "provider" not in cols:
            c.execute("ALTER TABLE connected_accounts ADD COLUMN provider TEXT DEFAULT 'google'")
        if "provider_account_id" not in cols:
            c.execute("ALTER TABLE connected_accounts ADD COLUMN provider_account_id TEXT")
            c.execute("UPDATE connected_accounts SET provider_account_id = id WHERE provider_account_id IS NULL")
        if "provider_email" not in cols:
            c.execute("ALTER TABLE connected_accounts ADD COLUMN provider_email TEXT")
            c.execute("UPDATE connected_accounts SET provider_email = email WHERE provider_email IS NULL")
        if "encrypted_refresh_token" not in cols:
            c.execute("ALTER TABLE connected_accounts ADD COLUMN encrypted_refresh_token TEXT")
        if "connection_status" not in cols:
            c.execute("ALTER TABLE connected_accounts ADD COLUMN connection_status TEXT DEFAULT 'active'")
        if "last_synced_at" not in cols:
            c.execute("ALTER TABLE connected_accounts ADD COLUMN last_synced_at TIMESTAMP")
            c.execute("UPDATE connected_accounts SET last_synced_at = connected_at WHERE last_synced_at IS NULL")
        if "expires_at" not in cols:
            c.execute("ALTER TABLE connected_accounts ADD COLUMN expires_at TIMESTAMP")
        if "price_per_year_inr" not in cols:
            c.execute("ALTER TABLE connected_accounts ADD COLUMN price_per_year_inr INTEGER DEFAULT 1")
        conn.commit()

    # Devices table
    c.execute("""
    CREATE TABLE IF NOT EXISTS devices (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        device_name TEXT NOT NULL,
        device_type TEXT NOT NULL DEFAULT 'android',
        last_active_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        device_status TEXT NOT NULL DEFAULT 'active',
        FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
    )
    """)

    # Populate devices from device_sessions if needed
    if table_exists("device_sessions"):
        c.execute("""
        INSERT OR IGNORE INTO devices (id, user_id, device_name, device_type, last_active_at, device_status)
        SELECT COALESCE(device_id, id), user_id, COALESCE(device_name, 'Android Device'), 'android', CURRENT_TIMESTAMP, 'active'
        FROM device_sessions
        """)
        conn.commit()

    # Backup files table
    c.execute("""
    CREATE TABLE IF NOT EXISTS backup_files (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        connected_account_id TEXT,
        google_drive_file_id TEXT,
        google_drive_folder_id TEXT,
        filename TEXT NOT NULL,
        mime_type TEXT NOT NULL,
        file_size INTEGER NOT NULL DEFAULT 0,
        checksum TEXT,
        backup_status TEXT NOT NULL DEFAULT 'completed',
        uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        local_path TEXT,
        file_type TEXT DEFAULT 'photo',
        cloud_web_url TEXT,
        FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
        FOREIGN KEY(connected_account_id) REFERENCES connected_accounts(id) ON DELETE SET NULL
    )
    """)

    # Backup history table
    c.execute("""
    CREATE TABLE IF NOT EXISTS backup_history (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        file_id TEXT,
        action TEXT NOT NULL DEFAULT 'upload',
        status TEXT NOT NULL DEFAULT 'success',
        source_device TEXT NOT NULL DEFAULT 'Android Device',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
        FOREIGN KEY(file_id) REFERENCES backup_files(id) ON DELETE SET NULL
    )
    """)

    # Storage usage table
    c.execute("""
    CREATE TABLE IF NOT EXISTS storage_usage (
        id TEXT PRIMARY KEY,
        connected_account_id TEXT UNIQUE NOT NULL,
        actual_quota INTEGER NOT NULL DEFAULT 16106127360,
        total_usage INTEGER NOT NULL DEFAULT 2147483648,
        available_storage INTEGER NOT NULL DEFAULT 13958643712,
        cloudvault_usage INTEGER NOT NULL DEFAULT 2147483648,
        last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY(connected_account_id) REFERENCES connected_accounts(id) ON DELETE CASCADE
    )
    """)

    # Storage targets table
    c.execute("""
    CREATE TABLE IF NOT EXISTS storage_targets (
        id TEXT PRIMARY KEY,
        connected_account_id TEXT UNIQUE NOT NULL,
        target_storage INTEGER NOT NULL DEFAULT 10737418240,
        reserved_storage INTEGER NOT NULL DEFAULT 2147483648,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY(connected_account_id) REFERENCES connected_accounts(id) ON DELETE CASCADE
    )
    """)

    # Upload queue table
    c.execute("""
    CREATE TABLE IF NOT EXISTS upload_queue (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        connected_account_id TEXT,
        file_metadata TEXT NOT NULL,
        upload_status TEXT NOT NULL DEFAULT 'queued',
        retry_count INTEGER DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
        FOREIGN KEY(connected_account_id) REFERENCES connected_accounts(id) ON DELETE SET NULL
    )
    """)

    # User settings table
    if table_exists("user_settings"):
        cols = get_columns("user_settings")
        if "id" not in cols:
            c.execute("ALTER TABLE user_settings ADD COLUMN id TEXT")
            c.execute("UPDATE user_settings SET id = user_id WHERE id IS NULL")
        if "auto_backup" not in cols:
            c.execute("ALTER TABLE user_settings ADD COLUMN auto_backup BOOLEAN DEFAULT 1")
            c.execute("UPDATE user_settings SET auto_backup = auto_backup_enabled WHERE auto_backup IS NULL AND auto_backup_enabled IS NOT NULL")
        if "photo_backup" not in cols:
            c.execute("ALTER TABLE user_settings ADD COLUMN photo_backup BOOLEAN DEFAULT 1")
            c.execute("UPDATE user_settings SET photo_backup = backup_photos WHERE photo_backup IS NULL AND backup_photos IS NOT NULL")
        if "video_backup" not in cols:
            c.execute("ALTER TABLE user_settings ADD COLUMN video_backup BOOLEAN DEFAULT 1")
            c.execute("UPDATE user_settings SET video_backup = backup_videos WHERE video_backup IS NULL AND backup_videos IS NOT NULL")
        if "document_backup" not in cols:
            c.execute("ALTER TABLE user_settings ADD COLUMN document_backup BOOLEAN DEFAULT 1")
            c.execute("UPDATE user_settings SET document_backup = backup_docs WHERE document_backup IS NULL AND backup_docs IS NOT NULL")
        conn.commit()

    # User sessions table
    c.execute("""
    CREATE TABLE IF NOT EXISTS user_sessions (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        device_id TEXT,
        session_status TEXT NOT NULL DEFAULT 'active',
        expires_at TIMESTAMP NOT NULL,
        session_token TEXT,
        refresh_token TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
        FOREIGN KEY(device_id) REFERENCES devices(id) ON DELETE CASCADE
    )
    """)

    # Migrate backup_catalog to backup_files if backup_files is empty
    c.execute("SELECT COUNT(*) FROM backup_files")
    bf_count = c.fetchone()[0]
    if bf_count == 0 and table_exists("backup_catalog"):
        print("Migrating rows from backup_catalog to backup_files...")
        c.execute("""
        INSERT OR IGNORE INTO backup_files (
            id, user_id, connected_account_id, google_drive_file_id, google_drive_folder_id,
            filename, mime_type, file_size, checksum, backup_status, uploaded_at,
            local_path, file_type, cloud_web_url
        )
        SELECT 
            id, user_id, account_id, cloud_file_id, remote_folder_id,
            file_name, mime_type, file_size_bytes, checksum_sha256,
            LOWER(COALESCE(status, 'completed')), uploaded_at,
            local_path, file_type, cloud_web_url
        FROM backup_catalog
        """)
        conn.commit()

        # Also populate backup_history
        c.execute("""
        INSERT OR IGNORE INTO backup_history (id, user_id, file_id, action, status, source_device, created_at)
        SELECT id || '_hist', user_id, id, 'upload', 'success', 'Android Phone', uploaded_at
        FROM backup_catalog
        """)
        conn.commit()

    # Populate storage_usage and storage_targets for all connected accounts
    c.execute("""
    INSERT OR IGNORE INTO storage_usage (id, connected_account_id, actual_quota, total_usage, available_storage, cloudvault_usage, last_updated)
    SELECT id || '_usage', id, 16106127360, 2147483648, 13958643712, 2147483648, CURRENT_TIMESTAMP
    FROM connected_accounts
    """)
    c.execute("""
    INSERT OR IGNORE INTO storage_targets (id, connected_account_id, target_storage, reserved_storage, updated_at)
    SELECT id || '_target', id, 10737418240, 2147483648, CURRENT_TIMESTAMP
    FROM connected_accounts
    """)
    conn.commit()

    # Migrate device_sessions to user_sessions if user_sessions is empty
    c.execute("SELECT COUNT(*) FROM user_sessions")
    if c.fetchone()[0] == 0 and table_exists("device_sessions"):
        c.execute("""
        INSERT OR IGNORE INTO user_sessions (id, user_id, device_id, session_status, expires_at, session_token, refresh_token, created_at)
        SELECT id, user_id, device_id, CASE WHEN is_active=1 THEN 'active' ELSE 'expired' END, expires_at, session_token, refresh_token, created_at
        FROM device_sessions
        """)
        conn.commit()

    # Subscriptions table
    c.execute("""
    CREATE TABLE IF NOT EXISTS subscriptions (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        plan_type TEXT NOT NULL DEFAULT 'annual_pass_inr_1',
        plan_name TEXT NOT NULL DEFAULT '₹1 Freedom Annual Pass',
        price_inr INTEGER NOT NULL DEFAULT 1,
        currency TEXT NOT NULL DEFAULT 'INR',
        status TEXT NOT NULL DEFAULT 'active',
        max_accounts INTEGER NOT NULL DEFAULT 999,
        valid_days INTEGER NOT NULL DEFAULT 365,
        starts_at TIMESTAMP NOT NULL,
        expires_at TIMESTAMP NOT NULL,
        auto_renew INTEGER NOT NULL DEFAULT 0,
        payment_method TEXT NOT NULL DEFAULT 'upi',
        transaction_id TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
    )
    """)

    # Transactions table
    c.execute("""
    CREATE TABLE IF NOT EXISTS transactions (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        subscription_id TEXT,
        amount INTEGER NOT NULL DEFAULT 1,
        currency TEXT NOT NULL DEFAULT 'INR',
        payment_method TEXT NOT NULL DEFAULT 'upi',
        payment_gateway TEXT NOT NULL DEFAULT 'upi_intent',
        gateway_ref TEXT,
        status TEXT NOT NULL DEFAULT 'success',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
        FOREIGN KEY(subscription_id) REFERENCES subscriptions(id) ON DELETE SET NULL
    )
    """)

    # Referrals table
    c.execute("""
    CREATE TABLE IF NOT EXISTS referrals (
        id TEXT PRIMARY KEY,
        referrer_id TEXT NOT NULL,
        referred_user_id TEXT,
        referred_email TEXT,
        referral_code TEXT NOT NULL,
        status TEXT NOT NULL DEFAULT 'completed',
        reward_granted INTEGER NOT NULL DEFAULT 0,
        reward_description TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        completed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY(referrer_id) REFERENCES users(id) ON DELETE CASCADE,
        FOREIGN KEY(referred_user_id) REFERENCES users(id) ON DELETE SET NULL
    )
    """)
    conn.commit()

    conn.close()
    print("Migration completed successfully with all tables fully aligned!")

if __name__ == '__main__':
    migrate_sqlite()
