import os
import sys
import hashlib
import secrets
import hmac
import uuid
import json
import logging
from datetime import datetime, timedelta
from functools import wraps
from dotenv import load_dotenv
import requests
import base64
import platform
import re

logger = logging.getLogger(__name__)

# Load environment variables from .env
load_dotenv(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.env'))
load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env'))

from flask import Flask, request, jsonify, send_file, redirect, Response, stream_with_context
from flask_cors import CORS
import jwt

# Add directory to sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from backend.config import config
from backend.database import db_session, init_db, DATABASE_URL
from backend.models import (
    User, ConnectedAccount, Device, BackupFile, BackupHistory,
    StorageUsage, StorageTarget, UploadQueue, UserSettings, UserSession,
    Subscription, Transaction, Referral
)

import sqlite3

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)

DB_PATH = os.environ.get('CLOUDVAULT_DB_PATH', os.path.join(os.path.dirname(__file__), 'cloudvault_central.db'))

def get_db():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def init_db():
    from backend.database import init_db as init_orm_db
    init_orm_db()
    conn = get_db()
    c = conn.cursor()
    c.execute('''
    CREATE TABLE IF NOT EXISTS backup_catalog (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        account_id TEXT,
        account_email TEXT,
        local_path TEXT,
        file_name TEXT NOT NULL,
        file_type TEXT NOT NULL,
        mime_type TEXT,
        file_size_bytes INTEGER DEFAULT 0,
        checksum_sha256 TEXT,
        cloud_file_id TEXT,
        cloud_web_url TEXT,
        status TEXT,
        created_at TEXT,
        uploaded_at TEXT,
        remote_folder_id TEXT
    )
    ''')
    c.execute('''
    CREATE TABLE IF NOT EXISTS device_sessions (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        device_id TEXT NOT NULL,
        device_name TEXT,
        session_token TEXT UNIQUE NOT NULL,
        refresh_token TEXT UNIQUE NOT NULL,
        created_at TEXT NOT NULL,
        expires_at TEXT NOT NULL,
        is_active INTEGER DEFAULT 1
    )
    ''')
    conn.commit()
    conn.close()

JWT_SECRET = config.JWT_SECRET
JWT_ALGORITHM = config.JWT_ALGORITHM
JWT_EXPIRATION_HOURS = config.JWT_EXPIRATION_HOURS
NAMESPACE_CLOUDVAULT = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')

UPLOAD_FOLDER = config.get_upload_folder()

# Helper functions
def generate_deterministic_user_id(email: str) -> str:
    return str(uuid.uuid5(NAMESPACE_CLOUDVAULT, f"cloudvault:user:{email.strip().lower()}"))

def generate_deterministic_account_id(user_id: str, email: str) -> str:
    return str(uuid.uuid5(NAMESPACE_CLOUDVAULT, f"cloudvault:acc:{user_id}:{email.strip().lower()}"))

def generate_deterministic_salt(email: str) -> str:
    data = f"cloudvault_salt_v2:{email.strip().lower()}:6ba7b810".encode('utf-8')
    return hashlib.sha256(data).hexdigest()

def hash_password(password: str, salt: str) -> str:
    return hashlib.sha256((password + salt).encode('utf-8')).hexdigest()

def generate_token(user_id: str, email: str, hours: int = JWT_EXPIRATION_HOURS) -> str:
    payload = {
        'sub': user_id,
        'email': email,
        'exp': datetime.utcnow() + timedelta(hours=hours),
        'iat': datetime.utcnow()
    }
    return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)

def decode_token(token: str):
    try:
        return jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
    except Exception:
        return None

def generate_referral_code(name: str = '', email: str = '', user_id: str = '') -> str:
    # 1. Clean first name
    first_name = (name or '').strip().split()[0] if name else ''
    clean_name = re.sub(r'[^A-Za-z]', '', first_name).upper()
    if len(clean_name) < 3:
        clean_name = re.sub(r'[^A-Za-z]', '', (email or '').split('@')[0]).upper()[:5]
    if len(clean_name) < 3:
        clean_name = 'ESPACE'
    else:
        clean_name = clean_name[:6]

    # 2. Check for digits in email (like nirajsen2710 -> 2710)
    email_digits = ''.join(re.findall(r'\d+', (email or '').split('@')[0]))
    if len(email_digits) >= 2:
        suffix = email_digits[:4]
    else:
        seed = f"{email}_{user_id}_{clean_name}".lower()
        suffix = hashlib.sha256(seed.encode()).hexdigest()[:4].upper()

    return f"{clean_name}{suffix}"

def auth_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth_header = request.headers.get('Authorization')
        token = None
        if auth_header and auth_header.startswith('Bearer '):
            token = auth_header.split(' ')[1]
        elif 'sessionToken' in request.headers:
            token = request.headers.get('sessionToken')

        if not token:
            # Check query params for downloads
            token = request.args.get('token')

        if not token:
            return jsonify({'error': 'Authorization token required', 'code': 'UNAUTHORIZED'}), 401

        payload = decode_token(token)
        if not payload:
            # Check user_sessions table as fallback for legacy sessions
            sess = db_session.query(UserSession).filter_by(session_token=token, session_status='active').first()
            if sess:
                user = db_session.query(User).filter_by(id=sess.user_id).first()
                if user:
                    request.current_user = user
                    return f(*args, **kwargs)
            return jsonify({'error': 'Invalid or expired token', 'code': 'TOKEN_EXPIRED'}), 401

        user = db_session.query(User).filter_by(id=payload['sub']).first()
        if not user or user.account_status != 'active':
            return jsonify({'error': 'User account not found or suspended', 'code': 'USER_NOT_FOUND'}), 401

        request.current_user = user
        return f(*args, **kwargs)
    return decorated

@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()

# ==========================================
# HEALTH & METADATA
# ==========================================
@app.route('/health', methods=['GET'])
def health():
    return jsonify({
        'status': 'healthy',
        'service': 'E Space Central Authentication Backend 2.0',
        'version': '2.0.0',
        'architecture': 'Cloud-First Google Drive Sync',
        'database': 'PostgreSQL/SQLite dual-engine',
        'timestamp': datetime.utcnow().isoformat()
    }), 200

# ==========================================
# PUBLIC APP CONFIGURATION ENDPOINT
# ==========================================
@app.route('/api/config/public', methods=['GET'])
def get_public_config():
    """Returns live public URLs and configurations to mobile apps and web clients"""
    return jsonify({
        'status': 'ok',
        'appName': 'E Space',
        'version': '2.0.0',
        'urls': {
            'baseUrl': config.BASE_URL,
            'frontendUrl': config.FRONTEND_URL,
            'productionUrl': getattr(config, 'PRODUCTION_URL', ''),
            'publicEdgeUrl': config.PUBLIC_EDGE_URL,
            'wifiBaseUrl': config.WIFI_BASE_URL,
        },
        'auth': {
            'googleClientId': config.GOOGLE_CLIENT_ID,
            'googleRedirectUri': config.get_oauth_redirect_uri(),
        },
        'payments': {
            'razorpayKeyId': config.RAZORPAY_KEY_ID,
            'razorpayPaymentUrl': config.RAZORPAY_PAYMENT_URL,
            'proPriceInr': config.PRO_PRICE_INR,
        },
        'referral': {
            'requiredCount': config.REFERRAL_VIP_REQUIRED_COUNT,
        }
    }), 200

# ==========================================
# AUTHENTICATION APIS
# ==========================================
@app.route('/api/auth/register', methods=['POST'])
def register():
    data = request.get_json(silent=True) or {}
    email = data.get('email', '').strip().lower()
    password = data.get('password', '').strip()
    name = (data.get('name') or data.get('displayName') or '').strip()
    device_id = data.get('deviceId') or str(uuid.uuid4())
    device_name = data.get('deviceName') or 'Android Device'
    device_type = data.get('deviceType') or 'android'

    if not email or not password:
        return jsonify({'error': 'Email and password are required'}), 400

    if not name:
        name = email.split('@')[0]

    existing = db_session.query(User).filter_by(email=email).first()
    if existing:
        return jsonify({'error': 'An account with this email already exists'}), 409

    user_id = generate_deterministic_user_id(email)
    salt = generate_deterministic_salt(email)
    pwd_hash = hash_password(password, salt)

    # Unique memorable fixed referral code
    ref_code = generate_referral_code(name, email, user_id)
    attempt = 1
    while db_session.query(User).filter_by(referral_code=ref_code).first():
        ref_code = f"{ref_code[:6]}{secrets.token_hex(2).upper()}"
        attempt += 1
        if attempt > 10:
            ref_code = f"ESPACE{secrets.token_hex(3).upper()}"
            break

    user = User(
        id=user_id,
        name=name,
        display_name=name,
        email=email,
        password_hash=pwd_hash,
        account_status='active',
        salt=salt,
        referral_code=ref_code,
        referral_count=0,
        created_at=datetime.utcnow(),
        updated_at=datetime.utcnow()
    )

    # Check incoming referral code
    incoming_ref = (data.get('referralCode') or data.get('referral_code') or '').strip().upper()
    if incoming_ref:
        referrer = db_session.query(User).filter_by(referral_code=incoming_ref).first()
        if referrer and referrer.id != user_id:
            user.referred_by_id = referrer.id
            referrer.referral_count = (referrer.referral_count or 0) + 1
            ref_record = Referral(
                id=str(uuid.uuid4()),
                referrer_id=referrer.id,
                referred_user_id=user_id,
                referred_email=email,
                referral_code=incoming_ref,
                status='completed',
                reward_granted=True,
                reward_description='Invited friend signed up',
                created_at=datetime.utcnow(),
                completed_at=datetime.utcnow()
            )
            db_session.add(ref_record)

            # If referrer invited 2 or more friends, unlock 1-Year VIP Pass for free!
            if referrer.referral_count >= 2:
                existing_vip = db_session.query(Subscription).filter_by(
                    user_id=referrer.id,
                    status='active'
                ).first()
                if not existing_vip:
                    vip_sub = Subscription(
                        id=str(uuid.uuid4()),
                        user_id=referrer.id,
                        plan_type='referral_vip',
                        plan_name='Referral VIP Pass (1 Year Free)',
                        price_inr=0,
                        currency='INR',
                        status='active',
                        max_accounts=999,
                        valid_days=365,
                        starts_at=datetime.utcnow(),
                        expires_at=datetime.utcnow() + timedelta(days=365),
                        auto_renew=False,
                        payment_method='referral_reward',
                        transaction_id=f"REF-VIP-{ref_record.id[:8]}"
                    )
                    db_session.add(vip_sub)

    db_session.add(user)
    db_session.flush()

    # User Settings
    settings = UserSettings(
        id=user_id,
        user_id=user_id,
        auto_backup=True,
        wifi_only=True,
        photo_backup=True,
        video_backup=True,
        document_backup=True,
        backup_quality='Original',
        storage_threshold_percent=90,
        notifications_enabled=True,
        schedule_interval_hours=4,
        updated_at=datetime.utcnow()
    )
    db_session.add(settings)

    # Register Device
    device = db_session.query(Device).filter_by(id=device_id).first()
    if not device:
        device = Device(
            id=device_id,
            user_id=user_id,
            device_name=device_name,
            device_type=device_type,
            last_active_at=datetime.utcnow(),
            device_status='active'
        )
        db_session.add(device)
    else:
        device.user_id = user_id
        device.last_active_at = datetime.utcnow()

    # Create Session & Tokens
    session_token = generate_token(user_id, email, hours=24)
    refresh_token = secrets.token_urlsafe(64)
    expires_at = datetime.utcnow() + timedelta(days=30)

    user_sess = UserSession(
        id=str(uuid.uuid4()),
        user_id=user_id,
        device_id=device_id,
        session_status='active',
        session_token=session_token,
        refresh_token=refresh_token,
        expires_at=expires_at,
        created_at=datetime.utcnow()
    )
    db_session.add(user_sess)
    db_session.commit()

    return jsonify({
        'message': 'User registered successfully',
        'user': user.to_dict(),
        'token': session_token,
        'sessionToken': session_token,
        'refreshToken': refresh_token,
        'expiresAt': expires_at.isoformat()
    }), 201

@app.route('/api/auth/login', methods=['POST'])
def login():
    data = request.get_json(silent=True) or {}
    email = data.get('email', '').strip().lower()
    password = data.get('password', '').strip()
    device_id = data.get('deviceId') or str(uuid.uuid4())
    device_name = data.get('deviceName') or 'Client Device'
    device_type = data.get('deviceType') or ('web' if 'web' in device_name.lower() else 'android')

    if not email or not password:
        return jsonify({'error': 'Email and password are required'}), 400

    user = db_session.query(User).filter_by(email=email).first()
    if not user:
        return jsonify({'error': 'Invalid email or password'}), 401

    salt = user.salt or generate_deterministic_salt(email)
    expected_hash = hash_password(password, salt)

    # Validate deterministic hash or raw hash
    if user.password_hash != expected_hash:
        # Check fallback salt
        alt_hash = hashlib.sha256((password + (user.salt or '')).encode('utf-8')).hexdigest()
        if user.password_hash != alt_hash:
            return jsonify({'error': 'Invalid email or password'}), 401

    if user.account_status != 'active':
        return jsonify({'error': 'Your account has been suspended'}), 403

    # Update or register device
    device = db_session.query(Device).filter_by(id=device_id).first()
    if not device:
        device = Device(
            id=device_id,
            user_id=user.id,
            device_name=device_name,
            device_type=device_type,
            last_active_at=datetime.utcnow(),
            device_status='active'
        )
        db_session.add(device)
    else:
        device.user_id = user.id
        device.last_active_at = datetime.utcnow()
        device.device_status = 'active'

    # Create Session Tokens
    session_token = generate_token(user.id, user.email, hours=24)
    refresh_token = secrets.token_urlsafe(64)
    expires_at = datetime.utcnow() + timedelta(days=30)

    user_sess = UserSession(
        id=str(uuid.uuid4()),
        user_id=user.id,
        device_id=device_id,
        session_status='active',
        session_token=session_token,
        refresh_token=refresh_token,
        expires_at=expires_at,
        created_at=datetime.utcnow()
    )
    db_session.add(user_sess)

    # Gather user data for instant cross-device restore
    settings = db_session.query(UserSettings).filter_by(user_id=user.id).first()
    accounts = db_session.query(ConnectedAccount).filter_by(user_id=user.id).all()
    backup_files = db_session.query(BackupFile).filter_by(user_id=user.id).limit(200).all()

    db_session.commit()

    return jsonify({
        'message': 'Login successful',
        'user': user.to_dict(),
        'token': session_token,
        'sessionToken': session_token,
        'refreshToken': refresh_token,
        'expiresAt': expires_at.isoformat(),
        'settings': settings.to_dict() if settings else None,
        'connectedAccounts': [a.to_dict() for a in accounts],
        'backupHistory': [f.to_dict() for f in backup_files]
    }), 200

@app.route('/api/auth/refresh', methods=['POST'])
def refresh_token():
    data = request.get_json(silent=True) or {}
    r_token = data.get('refreshToken')
    device_id = data.get('deviceId')

    if not r_token:
        return jsonify({'error': 'Refresh token required'}), 400

    query = db_session.query(UserSession).filter_by(refresh_token=r_token, session_status='active')
    if device_id:
        query = query.filter_by(device_id=device_id)

    sess = query.first()
    if not sess or sess.expires_at < datetime.utcnow():
        return jsonify({'error': 'Invalid or expired refresh token'}), 401

    user = db_session.query(User).filter_by(id=sess.user_id).first()
    if not user:
        return jsonify({'error': 'User not found'}), 401

    new_token = generate_token(user.id, user.email, hours=24)
    new_refresh = secrets.token_urlsafe(64)
    sess.session_token = new_token
    sess.refresh_token = new_refresh
    sess.expires_at = datetime.utcnow() + timedelta(days=30)
    db_session.commit()

    return jsonify({
        'token': new_token,
        'sessionToken': new_token,
        'refreshToken': new_refresh,
        'expiresAt': sess.expires_at.isoformat()
    }), 200

@app.route('/api/auth/logout', methods=['POST'])
@auth_required
def logout():
    data = request.get_json(silent=True) or {}
    logout_all = data.get('logoutAll', False)
    user_id = request.current_user.id

    if logout_all:
        db_session.query(UserSession).filter_by(user_id=user_id).update({'session_status': 'revoked'})
    else:
        auth_header = request.headers.get('Authorization', '')
        token = auth_header.replace('Bearer ', '').strip()
        db_session.query(UserSession).filter_by(session_token=token).update({'session_status': 'revoked'})

    db_session.commit()
    return jsonify({'message': 'Logged out successfully'}), 200

@app.route('/api/auth/me', methods=['GET'])
@auth_required
def get_current_user():
    user = request.current_user
    settings = db_session.query(UserSettings).filter_by(user_id=user.id).first()
    devices = db_session.query(Device).filter_by(user_id=user.id).all()
    accounts = db_session.query(ConnectedAccount).filter_by(user_id=user.id).all()
    last_session = db_session.query(UserSession).filter_by(user_id=user.id).order_by(UserSession.created_at.desc()).first()
    last_login = last_session.created_at.isoformat() if last_session else (user.updated_at.isoformat() if user.updated_at else (user.created_at.isoformat() if user.created_at else None))

    return jsonify({
        'user': user.to_dict(),
        'userId': user.id,
        'email': user.email,
        'name': user.name or user.display_name,
        'accountStatus': user.account_status or 'active',
        'createdAt': user.created_at.isoformat() if user.created_at else None,
        'lastLogin': last_login,
        'settings': settings.to_dict() if settings else None,
        'devices': [d.to_dict() for d in devices],
        'devicesCount': len(devices),
        'connectedAccounts': [a.to_dict() for a in accounts],
        'securityInfo': {
            'hasPassword': bool(user.password_hash),
            'twoFactorEnabled': False,
            'sessionsCount': db_session.query(UserSession).filter_by(user_id=user.id, session_status='active').count()
        }
    }), 200

@app.route('/api/auth/change-password', methods=['POST'])
@auth_required
def change_password():
    data = request.get_json(silent=True) or {}
    current_password = data.get('currentPassword', '').strip()
    new_password = data.get('newPassword', '').strip()

    if not current_password or not new_password:
        return jsonify({'error': 'Current and new password are required'}), 400

    user = request.current_user
    salt = user.salt or generate_deterministic_salt(user.email)
    expected_hash = hash_password(current_password, salt)

    if user.password_hash != expected_hash:
        alt_hash = hashlib.sha256((current_password + (user.salt or '')).encode('utf-8')).hexdigest()
        if user.password_hash != alt_hash:
            return jsonify({'error': 'Current password does not match'}), 401

    new_salt = generate_deterministic_salt(user.email)
    user.salt = new_salt
    user.password_hash = hash_password(new_password, new_salt)
    user.updated_at = datetime.utcnow()
    db_session.commit()

    return jsonify({'message': 'Password updated successfully'}), 200

@app.route('/api/auth/forgot-password', methods=['POST'])
def forgot_password():
    data = request.get_json(silent=True) or {}
    email = data.get('email', '').strip().lower()
    new_password = data.get('newPassword', '').strip()

    if not email or not new_password:
        return jsonify({'error': 'Email and new password are required'}), 400

    user = db_session.query(User).filter_by(email=email).first()
    if not user:
        return jsonify({'error': 'Account not found with this email'}), 404

    salt = user.salt or generate_deterministic_salt(email)
    user.password_hash = hash_password(new_password, salt)
    user.updated_at = datetime.utcnow()
    db_session.commit()

    return jsonify({'message': 'Password reset successfully'}), 200

# ==========================================
# DEVICES APIS
# ==========================================
@app.route('/api/devices', methods=['GET'])
@auth_required
def list_devices():
    devices = db_session.query(Device).filter_by(user_id=request.current_user.id).order_by(Device.last_active_at.desc()).all()
    return jsonify({'devices': [d.to_dict() for d in devices]}), 200

@app.route('/api/devices', methods=['POST'])
@auth_required
def register_device():
    data = request.get_json(silent=True) or {}
    device_id = data.get('deviceId') or str(uuid.uuid4())
    device_name = data.get('deviceName', 'Unknown Device')
    device_type = data.get('deviceType', 'web')

    device = db_session.query(Device).filter_by(id=device_id).first()
    if not device:
        device = Device(
            id=device_id,
            user_id=request.current_user.id,
            device_name=device_name,
            device_type=device_type,
            last_active_at=datetime.utcnow(),
            device_status='active'
        )
        db_session.add(device)
    else:
        device.device_name = device_name
        device.device_type = device_type
        device.last_active_at = datetime.utcnow()
        device.device_status = 'active'

    db_session.commit()
    return jsonify({'message': 'Device registered', 'device': device.to_dict()}), 200

@app.route('/api/devices/<device_id>', methods=['DELETE'])
@auth_required
def revoke_device(device_id):
    device = db_session.query(Device).filter_by(id=device_id, user_id=request.current_user.id).first()
    if not device:
        return jsonify({'error': 'Device not found'}), 404

    device.device_status = 'revoked'
    db_session.query(UserSession).filter_by(device_id=device_id).update({'session_status': 'revoked'})
    db_session.commit()
    return jsonify({'message': 'Device access revoked'}), 200

# ==========================================
# GOOGLE DRIVE & CONNECTED ACCOUNTS APIS
# ==========================================
ENV_FILE_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.env')

@app.route('/api/drive/oauth-config', methods=['GET', 'POST'])
@auth_required
def drive_oauth_config():
    """Get or save Google Cloud OAuth Web Client ID and Secret"""
    if request.method == 'GET':
        client_id = os.environ.get('GOOGLE_CLIENT_ID', '')
        client_secret = os.environ.get('GOOGLE_CLIENT_SECRET', '')
        return jsonify({
            'clientId': client_id,
            'isConfigured': bool(client_id and client_secret),
            'redirectUri': f"{request.host_url.rstrip('/')}/api/drive/callback"
        }), 200

    data = request.get_json(silent=True) or {}
    new_client_id = (data.get('clientId') or '').strip()
    new_client_secret = (data.get('clientSecret') or '').strip()

    if not new_client_id:
        return jsonify({'error': 'Client ID is required'}), 400

    os.environ['GOOGLE_CLIENT_ID'] = new_client_id
    if new_client_secret:
        os.environ['GOOGLE_CLIENT_SECRET'] = new_client_secret

    # Persist to .env file
    try:
        lines = []
        if os.path.exists(ENV_FILE_PATH):
            with open(ENV_FILE_PATH, 'r') as f:
                lines = [l for l in f.readlines() if not l.startswith('GOOGLE_CLIENT_ID=') and not l.startswith('GOOGLE_CLIENT_SECRET=')]
        lines.append(f"GOOGLE_CLIENT_ID={new_client_id}\n")
        if new_client_secret:
            lines.append(f"GOOGLE_CLIENT_SECRET={new_client_secret}\n")
        with open(ENV_FILE_PATH, 'w') as f:
            f.writelines(lines)
    except Exception as e:
        logger.warning(f"Could not persist to .env file: {e}")

    return jsonify({
        'message': 'Google OAuth credentials updated successfully',
        'isConfigured': bool(new_client_id and (new_client_secret or os.environ.get('GOOGLE_CLIENT_SECRET')))
    }), 200

def get_effective_redirect_uri():
    """Generates proper HTTPS/HTTP callback URL preserving reverse-proxy headers or .env configuration"""
    configured = os.environ.get('GOOGLE_REDIRECT_URI')
    if configured and not ('127.0.0.1' in configured and request.headers.get('X-Forwarded-Host')):
        return configured
    host = request.headers.get('X-Forwarded-Host') or request.host
    scheme = request.headers.get('X-Forwarded-Proto') or request.scheme
    if 'trycloudflare.com' in host or 'trycloudflare.com' in request.host_url:
        scheme = 'https'
    return f"{scheme}://{host}/api/drive/callback"

@app.route('/api/drive/auth-url', methods=['GET'])
@auth_required
def get_drive_auth_url():
    # Standard Google Drive OAuth URL configuration
    client_id = os.environ.get('GOOGLE_CLIENT_ID', 'cloudvault-client-id.apps.googleusercontent.com')
    redirect_uri = request.args.get('redirectUri') or get_effective_redirect_uri()
    scopes = [
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/drive.file',
        'https://www.googleapis.com/auth/userinfo.email',
        'https://www.googleapis.com/auth/userinfo.profile'
    ]
    scope_str = " ".join(scopes)
    b64_uri = base64.urlsafe_b64encode(redirect_uri.encode('utf-8')).decode('utf-8').rstrip('=')
    state_token = f"{request.current_user.id}___{b64_uri}"

    auth_url = (
        f"https://accounts.google.com/o/oauth2/v2/auth?"
        f"client_id={client_id}&"
        f"redirect_uri={redirect_uri}&"
        f"response_type=code&"
        f"scope={scope_str}&"
        f"access_type=offline&"
        f"prompt=consent&"
        f"state={state_token}"
    )
    print(f"Generated OAuth URL for user {request.current_user.id} with redirect_uri: {redirect_uri}", flush=True)
    return jsonify({
        'authUrl': auth_url,
        'clientId': client_id,
        'redirectUri': redirect_uri,
        'scopes': scopes,
        'isConfigured': bool(os.environ.get('GOOGLE_CLIENT_ID') and os.environ.get('GOOGLE_CLIENT_SECRET'))
    }), 200

@app.route('/api/drive/callback', methods=['GET', 'POST'])
def drive_oauth_callback():
    """Handles OAuth 2.0 redirect from Google consent screen"""
    code = request.args.get('code')
    raw_state = request.args.get('state') or ''
    error = request.args.get('error')

    frontend_redirect = "/accounts"

    if error or not code:
        print(f"OAuth Callback error or no code. error={error}, code={bool(code)}", flush=True)
        return redirect(f"{frontend_redirect}?oauth_status=error&msg={error or 'cancelled'}")

    client_id = os.environ.get('GOOGLE_CLIENT_ID', '')
    client_secret = os.environ.get('GOOGLE_CLIENT_SECRET', '')
    
    state_user_id = raw_state
    redirect_uri = get_effective_redirect_uri()

    if '___' in raw_state:
        try:
            parts = raw_state.split('___', 1)
            state_user_id = parts[0]
            pad = len(parts[1]) % 4
            b64_str = parts[1] + ('=' * (4 - pad) if pad else '')
            decoded_uri = base64.urlsafe_b64decode(b64_str.encode('utf-8')).decode('utf-8')
            if decoded_uri.startswith('http'):
                redirect_uri = decoded_uri
        except Exception as e:
            print(f"Could not decode redirect_uri from state: {e}", flush=True)

    print(f"OAuth Callback received! Code prefix: {code[:10]}..., user: {state_user_id}, redirect_uri: {redirect_uri}", flush=True)

    if not client_id or not client_secret:
        print("Missing GOOGLE_CLIENT_ID or GOOGLE_CLIENT_SECRET on server!", flush=True)
        return redirect(f"{frontend_redirect}?oauth_status=error&msg=missing_credentials_on_server")

    # Exchange authorization code for live Google access & refresh tokens
    try:
        token_res = requests.post(
            'https://oauth2.googleapis.com/token',
            data={
                'code': code,
                'client_id': client_id,
                'client_secret': client_secret,
                'redirect_uri': redirect_uri,
                'grant_type': 'authorization_code'
            },
            timeout=15
        )
        print("GOOGLE TOKEN EXCHANGE:", token_res.status_code, token_res.text, flush=True)
    except Exception as e:
        print("GOOGLE TOKEN REQUEST EXCEPTION:", e, flush=True)
        return redirect(f"{frontend_redirect}?oauth_status=error&msg=token_request_failed_{type(e).__name__}")

    if token_res.status_code != 200:
        err_msg = 'invalid_token_response'
        try:
            err_json = token_res.json()
            err_msg = err_json.get('error_description') or err_json.get('error') or err_msg
        except Exception:
            pass
        return redirect(f"{frontend_redirect}?oauth_status=error&msg={err_msg}")

    token_data = token_res.json()
    access_token = token_data.get('access_token')
    refresh_token = token_data.get('refresh_token') or access_token

    # Fetch authorized Google user profile
    try:
        uinfo_res = requests.get(
            'https://www.googleapis.com/oauth2/v2/userinfo',
            headers={'Authorization': f'Bearer {access_token}'},
            timeout=10
        )
        userinfo = uinfo_res.json() if uinfo_res.status_code == 200 else {}
    except Exception:
        userinfo = {}

    google_email = (userinfo.get('email') or '').strip().lower()
    google_name = userinfo.get('name') or (google_email.split('@')[0] if google_email else 'Google Drive')
    google_photo = userinfo.get('picture')
    provider_id = userinfo.get('id') or str(uuid.uuid4())

    if not google_email:
        return redirect(f"{frontend_redirect}?oauth_status=error&msg=no_email_returned")

    # Identify master user
    target_user = None
    if state_user_id:
        target_user = db_session.query(User).filter_by(id=state_user_id).first()
    if not target_user:
        target_user = db_session.query(User).first()
    if not target_user:
        return redirect(f"{frontend_redirect}?oauth_status=error&msg=no_user_found")

    # Find or create connected account
    acc = db_session.query(ConnectedAccount).filter_by(
        user_id=target_user.id,
        provider_email=google_email
    ).first()

    # Query live Google Drive storage quota
    total_quota = 16106127360
    total_used = 0
    try:
        about_res = requests.get(
            'https://www.googleapis.com/drive/v3/about',
            headers={'Authorization': f'Bearer {access_token}'},
            params={'fields': 'storageQuota'},
            timeout=10
        )
        if about_res.status_code == 200:
            sq = about_res.json().get('storageQuota', {})
            total_quota = int(sq.get('limit', 16106127360))
            total_used = int(sq.get('usage', 0))
    except Exception:
        pass

    if acc:
        acc.encrypted_refresh_token = refresh_token
        acc.connection_status = 'active'
        acc.display_name = google_name
        if google_photo:
            acc.photo_url = google_photo
        acc.last_synced_at = datetime.utcnow()

        # Update StorageUsage
        usage = db_session.query(StorageUsage).filter_by(connected_account_id=acc.id).first()
        if usage:
            usage.actual_quota = total_quota
            usage.total_usage = total_used
            usage.available_storage = max(0, total_quota - total_used)
            usage.last_updated = datetime.utcnow()
    else:
        is_first = db_session.query(ConnectedAccount).filter_by(user_id=target_user.id).count() == 0
        acc_id = generate_deterministic_account_id(target_user.id, google_email)
        acc = ConnectedAccount(
            id=acc_id,
            user_id=target_user.id,
            provider='google',
            provider_account_id=provider_id,
            provider_email=google_email,
            email=google_email,
            encrypted_refresh_token=refresh_token,
            connection_status='active',
            display_name=google_name,
            photo_url=google_photo,
            is_active_backup=is_first,
            created_at=datetime.utcnow(),
            connected_at=datetime.utcnow(),
            updated_at=datetime.utcnow(),
            last_synced_at=datetime.utcnow()
        )
        db_session.add(acc)
        db_session.flush()

        db_session.add(StorageUsage(
            id=str(uuid.uuid4()),
            connected_account_id=acc.id,
            actual_quota=total_quota,
            total_usage=total_used,
            available_storage=max(0, total_quota - total_used),
            cloudvault_usage=0,
            last_updated=datetime.utcnow()
        ))

        db_session.add(StorageTarget(
            id=str(uuid.uuid4()),
            connected_account_id=acc.id,
            target_storage=10737418240,
            reserved_storage=2147483648,
            updated_at=datetime.utcnow()
        ))

    # Auto-link and auto-sync any orphaned BackupFile records for this user
    orphaned_files = db_session.query(BackupFile).filter_by(
        user_id=target_user.id,
        connected_account_id=None
    ).all()
    for ofile in orphaned_files:
        ofile.connected_account_id = acc.id
        try:
            for fname in os.listdir(UPLOAD_FOLDER):
                if fname.endswith(ofile.filename):
                    fpath = os.path.join(UPLOAD_FOLDER, fname)
                    with open(fpath, 'rb') as f:
                        f_bytes = f.read()
                    rid, rurl = try_upload_to_real_google_drive(acc, f_bytes, ofile.filename, ofile.mime_type, ofile.file_type)
                    if rid:
                        ofile.google_drive_file_id = rid
                        ofile.cloud_web_url = rurl or ofile.cloud_web_url
                    break
        except Exception as e:
            print(f"Auto-sync file {ofile.filename} to Google Drive error: {e}", flush=True)

    # Immediately discover any existing files in this Google Drive
    try:
        disc_count = discover_google_drive_files(acc, target_user.id)
        print(f"Discovered {disc_count} existing files from Google Drive for {google_email}", flush=True)
    except Exception as e:
        print(f"Remote file discovery error: {e}", flush=True)

    db_session.commit()
    return redirect(f"{frontend_redirect}?oauth_status=success&email={google_email}")

# ==========================================
# CLOUD PROVIDERS DIRECTORY & GLOBAL CATALOG
# ==========================================
PROVIDER_QUOTAS = {
    'google': 15 * 1024 * 1024 * 1024,      # 15 GB
    'mega': 20 * 1024 * 1024 * 1024,        # 20 GB
    'terabox': 1024 * 1024 * 1024 * 1024,   # 1024 GB (1 TB)
    'box': 10 * 1024 * 1024 * 1024,         # 10 GB
    'pcloud': 10 * 1024 * 1024 * 1024,      # 10 GB
    'onedrive': 5 * 1024 * 1024 * 1024,     # 5 GB
    'degoo': 20 * 1024 * 1024 * 1024,       # 20 GB
    'icedrive': 10 * 1024 * 1024 * 1024,    # 10 GB
    'proton': 5 * 1024 * 1024 * 1024,       # 5 GB
    'dropbox': 2 * 1024 * 1024 * 1024,      # 2 GB
    'yandex': 10 * 1024 * 1024 * 1024,      # 10 GB
    'koofr': 10 * 1024 * 1024 * 1024        # 10 GB
}

CLOUD_PROVIDERS_CATALOG = [
    {
        "id": "google",
        "name": "Google Drive",
        "category": "Global Leader",
        "freeGB": 15,
        "signupUrl": "https://accounts.google.com/signup",
        "loginUrl": "https://accounts.google.com/signin",
        "authType": "oauth",
        "badge": "Most Popular",
        "accentColor": "0xFF4285F4",
        "description": "15 GB free per account across Gmail, Drive & Photos. Connect multiple accounts for 30GB, 45GB, 60GB+."
    },
    {
        "id": "mega",
        "name": "Mega.nz",
        "category": "Encrypted Cloud",
        "freeGB": 20,
        "signupUrl": "https://mega.nz/register",
        "loginUrl": "https://mega.nz/login",
        "authType": "credentials",
        "badge": "20 GB Free",
        "accentColor": "0xFFD92727",
        "description": "20 GB end-to-end encrypted free cloud storage with fast global sync."
    },
    {
        "id": "terabox",
        "name": "TeraBox",
        "category": "Massive Storage",
        "freeGB": 1024,
        "signupUrl": "https://www.terabox.com/",
        "loginUrl": "https://www.terabox.com/main",
        "authType": "credentials",
        "badge": "1,024 GB (1 TB)",
        "accentColor": "0xFF0F52BA",
        "description": "1,024 GB (1 TB) massive free storage for high-res photo albums and 4K videos."
    },
    {
        "id": "box",
        "name": "Box.com",
        "category": "Enterprise Cloud",
        "freeGB": 10,
        "signupUrl": "https://account.box.com/signup/n/personal",
        "loginUrl": "https://account.box.com/login",
        "authType": "credentials",
        "badge": "10 GB Free",
        "accentColor": "0xFF0061D5",
        "description": "10 GB secure cloud storage with strict enterprise isolation and versioning."
    },
    {
        "id": "pcloud",
        "name": "pCloud",
        "category": "Media & Streaming",
        "freeGB": 10,
        "signupUrl": "https://my.pcloud.com/#page=register",
        "loginUrl": "https://my.pcloud.com/",
        "authType": "credentials",
        "badge": "10 GB Free",
        "accentColor": "0xFF179BD7",
        "description": "Up to 10 GB free cloud storage featuring integrated video streaming player."
    },
    {
        "id": "onedrive",
        "name": "Microsoft OneDrive",
        "category": "Productivity Cloud",
        "freeGB": 5,
        "signupUrl": "https://signup.live.com/",
        "loginUrl": "https://login.live.com/",
        "authType": "oauth",
        "badge": "Microsoft 365",
        "accentColor": "0xFF0078D4",
        "description": "5 GB free storage seamlessly integrated with Microsoft 365."
    },
    {
        "id": "degoo",
        "name": "Degoo Cloud",
        "category": "Photo Backup",
        "freeGB": 20,
        "signupUrl": "https://app.degoo.com/login",
        "loginUrl": "https://app.degoo.com/login",
        "authType": "credentials",
        "badge": "20 GB Free",
        "accentColor": "0xFF25D366",
        "description": "20 GB dedicated free space for camera photos and videos."
    },
    {
        "id": "icedrive",
        "name": "IceDrive",
        "category": "Next-Gen Storage",
        "freeGB": 10,
        "signupUrl": "https://icedrive.net/login#register",
        "loginUrl": "https://icedrive.net/login",
        "authType": "credentials",
        "badge": "Twofish Encryption",
        "accentColor": "0xFF00B4D8",
        "description": "10 GB next-generation encrypted cloud storage with revolutionary clean UI."
    },
    {
        "id": "proton",
        "name": "Proton Drive",
        "category": "Swiss Privacy",
        "freeGB": 5,
        "signupUrl": "https://account.proton.me/drive/signup",
        "loginUrl": "https://account.proton.me/drive",
        "authType": "credentials",
        "badge": "Swiss Privacy",
        "accentColor": "0xFF6D4AFF",
        "description": "5 GB Swiss privacy-focused encrypted storage under strict privacy laws."
    },
    {
        "id": "dropbox",
        "name": "Dropbox",
        "category": "Industry Standard",
        "freeGB": 2,
        "signupUrl": "https://www.dropbox.com/register",
        "loginUrl": "https://www.dropbox.com/login",
        "authType": "oauth",
        "badge": "Universal Sync",
        "accentColor": "0xFF0061FF",
        "description": "2 GB reliable cloud storage with ultra-fast delta synchronization."
    },
    {
        "id": "yandex",
        "name": "Yandex Disk",
        "category": "High Speed Cloud",
        "freeGB": 10,
        "signupUrl": "https://passport.yandex.com/registration",
        "loginUrl": "https://passport.yandex.com/auth",
        "authType": "credentials",
        "badge": "10 GB Free",
        "accentColor": "0xFFFF0000",
        "description": "10 GB fast cloud storage with auto-sync and mobile client compatibility."
    },
    {
        "id": "koofr",
        "name": "Koofr",
        "category": "EU Privacy Cloud",
        "freeGB": 10,
        "signupUrl": "https://app.koofr.net/signup",
        "loginUrl": "https://app.koofr.net/login",
        "authType": "credentials",
        "badge": "No Tracking",
        "accentColor": "0xFF1C9963",
        "description": "10 GB European privacy-respecting cloud storage without ad tracking."
    }
]

@app.route('/api/cloud-providers', methods=['GET'])
def get_cloud_providers():
    total_free_gb = sum(p['freeGB'] for p in CLOUD_PROVIDERS_CATALOG)
    return jsonify({
        'providers': CLOUD_PROVIDERS_CATALOG,
        'totalProviders': len(CLOUD_PROVIDERS_CATALOG),
        'totalFreeStorageGB': total_free_gb,
        'pricePerAccountPerYearInr': 1.00,
        'currency': 'INR',
        'upiIntent': 'upi://pay?pa=espace@upi&pn=ESpace%20Storage&am=1.00&cu=INR&tn=ESpace%20Link%20Cloud%20Account'
    }), 200

@app.route('/api/drive/accounts', methods=['GET'])
@app.route('/api/cloud/accounts', methods=['GET'])
@auth_required
def list_connected_accounts():
    accounts = db_session.query(ConnectedAccount).filter_by(user_id=request.current_user.id).all()
    return jsonify({'accounts': [a.to_dict() for a in accounts]}), 200

@app.route('/api/drive/accounts', methods=['POST'])
@app.route('/api/cloud/accounts', methods=['POST'])
@auth_required
def connect_account():
    data = request.get_json(silent=True) or {}
    provider = (data.get('provider') or 'google').strip().lower()
    email = (data.get('email') or data.get('providerEmail') or '').strip().lower()
    display_name = data.get('displayName') or f"{provider.title()} ({email.split('@')[0]})"
    provider_id = data.get('providerAccountId') or str(uuid.uuid4())
    photo_url = data.get('photoUrl')
    refresh_token_enc = data.get('refreshToken') or data.get('accountToken') or data.get('password') or 'token_stored_locally'
    payment_confirmed = bool(data.get('paymentConfirmed') or data.get('isPaid') or data.get('gatewayRef'))

    if not email:
        return jsonify({'error': 'Account email or username is required'}), 400

    existing = db_session.query(ConnectedAccount).filter_by(
        user_id=request.current_user.id,
        provider_email=email,
        provider=provider
    ).first()

    if existing:
        existing.connection_status = 'active'
        existing.last_synced_at = datetime.utcnow()
        if photo_url:
            existing.photo_url = photo_url
        if refresh_token_enc:
            existing.encrypted_refresh_token = refresh_token_enc
        acc = existing
    else:
        # Check active accounts count and subscription
        active_count = db_session.query(ConnectedAccount).filter_by(
            user_id=request.current_user.id,
            connection_status='active'
        ).count()

        sub = db_session.query(Subscription).filter_by(
            user_id=request.current_user.id,
            status='active'
        ).order_by(Subscription.expires_at.desc()).first()

        has_active_pass = sub is not None and sub.is_active

        # Rule: ₹1 charged per account per year (or covered by active annual pass, or 1st account on free trial)
        can_add = has_active_pass or (active_count == 0) or payment_confirmed

        if not can_add:
            return jsonify({
                'error': f'Connecting an additional {provider.title()} account costs ₹1/year. Complete ₹1 UPI payment to activate.',
                'code': 'PAYMENT_REQUIRED',
                'requiresPayment': True,
                'requiresSubscription': True,
                'pricePerAccountInr': 1.00,
                'provider': provider,
                'currentAccounts': active_count,
                'currency': 'INR',
                'upiIntent': 'upi://pay?pa=espace@upi&pn=ESpace%20Storage&am=1.00&cu=INR&tn=ESpace%20Link%20Cloud%20Account'
            }), 403

        is_first = active_count == 0
        acc_id = data.get('id') or str(uuid.uuid4())
        acc = ConnectedAccount(
            id=acc_id,
            user_id=request.current_user.id,
            provider=provider,
            provider_account_id=provider_id,
            provider_email=email,
            email=email,
            encrypted_refresh_token=refresh_token_enc,
            connection_status='active',
            display_name=display_name,
            photo_url=photo_url,
            is_active_backup=is_first,
            expires_at=datetime.utcnow() + timedelta(days=365),
            price_per_year_inr=1,
            created_at=datetime.utcnow(),
            connected_at=datetime.utcnow(),
            updated_at=datetime.utcnow(),
            last_synced_at=datetime.utcnow()
        )
        db_session.add(acc)
        db_session.flush()

        # Quota allocation from global catalog
        quota_bytes = PROVIDER_QUOTAS.get(provider, 15 * 1024 * 1024 * 1024)

        usage = StorageUsage(
            id=str(uuid.uuid4()),
            connected_account_id=acc.id,
            actual_quota=quota_bytes,
            total_usage=0,
            available_storage=quota_bytes,
            cloudvault_usage=0,
            last_updated=datetime.utcnow()
        )
        db_session.add(usage)

        target = StorageTarget(
            id=str(uuid.uuid4()),
            connected_account_id=acc.id,
            target_storage=int(quota_bytes * 0.7),
            reserved_storage=int(quota_bytes * 0.3),
            updated_at=datetime.utcnow()
        )
        db_session.add(target)

        # Record ₹1 Transaction for adding this account
        txn = Transaction(
            id=str(uuid.uuid4()),
            user_id=request.current_user.id,
            amount=1,
            currency='INR',
            payment_method=data.get('paymentMethod', 'upi'),
            payment_gateway='upi_intent',
            gateway_ref=data.get('gatewayRef') or f"ACC-LINK-{secrets.token_hex(4).upper()}",
            status='success',
            created_at=datetime.utcnow()
        )
        db_session.add(txn)

    db_session.commit()
    return jsonify({
        'message': f'{provider.title()} account connected successfully for 1 year!',
        'account': acc.to_dict()
    }), 201

@app.route('/api/drive/accounts/<account_id>/renew', methods=['POST'])
@app.route('/api/cloud/accounts/<account_id>/renew', methods=['POST'])
@auth_required
def renew_account(account_id):
    acc = db_session.query(ConnectedAccount).filter_by(id=account_id, user_id=request.current_user.id).first()
    if not acc:
        return jsonify({'error': 'Account not found'}), 404

    now = datetime.utcnow()
    if acc.expires_at and acc.expires_at > now:
        acc.expires_at = acc.expires_at + timedelta(days=365)
    else:
        acc.expires_at = now + timedelta(days=365)
    acc.connection_status = 'active'
    acc.updated_at = now

    txn = Transaction(
        id=str(uuid.uuid4()),
        user_id=request.current_user.id,
        amount=1,
        currency='INR',
        payment_method='upi_intent',
        payment_gateway='upi_intent',
        gateway_ref=f"RENEW-ACC-{secrets.token_hex(4).upper()}",
        status='success',
        created_at=now
    )
    db_session.add(txn)
    db_session.commit()

    return jsonify({
        'message': f'Account {acc.provider_email} renewed for 1 year for ₹1!',
        'account': acc.to_dict()
    }), 200

@app.route('/api/drive/accounts/<account_id>', methods=['DELETE'])
@auth_required
def disconnect_account(account_id):
    acc = db_session.query(ConnectedAccount).filter_by(id=account_id, user_id=request.current_user.id).first()
    if not acc:
        return jsonify({'error': 'Account not found'}), 404

    db_session.delete(acc)
    db_session.commit()
    return jsonify({'message': 'Connected account removed'}), 200

@app.route('/api/drive/accounts/<account_id>/set-active', methods=['POST'])
@auth_required
def set_active_account(account_id):
    accounts = db_session.query(ConnectedAccount).filter_by(user_id=request.current_user.id).all()
    found = False
    for a in accounts:
        if a.id == account_id:
            a.is_active_backup = True
            found = True
        else:
            a.is_active_backup = False

    if not found:
        return jsonify({'error': 'Account not found'}), 404

    db_session.commit()
    return jsonify({'message': 'Active backup account updated'}), 200

@app.route('/api/drive/accounts/<account_id>/sync', methods=['POST'])
@auth_required
def sync_account(account_id):
    acc = db_session.query(ConnectedAccount).filter_by(id=account_id, user_id=request.current_user.id).first()
    if not acc:
        return jsonify({'error': 'Account not found'}), 404

    acc.last_synced_at = datetime.utcnow()
    new_found = discover_google_drive_files(acc, request.current_user.id)

    # Recalculate file usage
    files = db_session.query(BackupFile).filter_by(connected_account_id=acc.id).all()
    total_file_bytes = sum(f.file_size for f in files)
    if acc.storage_usage:
        acc.storage_usage.cloudvault_usage = total_file_bytes
        acc.storage_usage.last_updated = datetime.utcnow()

    db_session.commit()
    return jsonify({
        'message': f'Account {acc.provider_email} synchronized successfully',
        'account': acc.to_dict(),
        'filesCount': len(files),
        'cloudvaultUsage': total_file_bytes,
        'newDiscoveredFiles': new_found
    }), 200

@app.route('/api/drive/accounts/<account_id>/refresh-quota', methods=['POST'])
@auth_required
def refresh_account_quota(account_id):
    acc = db_session.query(ConnectedAccount).filter_by(id=account_id, user_id=request.current_user.id).first()
    if not acc:
        return jsonify({'error': 'Account not found'}), 404

    if acc.storage_usage:
        acc.storage_usage.last_updated = datetime.utcnow()
    acc.last_synced_at = datetime.utcnow()
    db_session.commit()

    return jsonify({
        'message': 'Storage quota refreshed',
        'account': acc.to_dict()
    }), 200

@app.route('/api/drive/accounts/<account_id>/target', methods=['PUT', 'POST'])
@auth_required
def set_account_target(account_id):
    acc = db_session.query(ConnectedAccount).filter_by(id=account_id, user_id=request.current_user.id).first()
    if not acc:
        return jsonify({'error': 'Account not found'}), 404

    data = request.get_json(silent=True) or {}
    target_gb = data.get('targetStorageGB') or data.get('targetGB')
    if target_gb is None:
        return jsonify({'error': 'targetStorageGB is required'}), 400

    target_bytes = int(float(target_gb) * 1024 * 1024 * 1024)
    quota = acc.storage_usage.actual_quota if acc.storage_usage else 16106127360
    reserved_bytes = max(0, quota - target_bytes)

    target = db_session.query(StorageTarget).filter_by(connected_account_id=acc.id).first()
    if not target:
        target = StorageTarget(
            id=f"{acc.id}_target",
            connected_account_id=acc.id,
            target_storage=target_bytes,
            reserved_storage=reserved_bytes,
            updated_at=datetime.utcnow()
        )
        db_session.add(target)
    else:
        target.target_storage = target_bytes
        target.reserved_storage = reserved_bytes
        target.updated_at = datetime.utcnow()

    db_session.commit()
    return jsonify({
        'message': 'Target updated successfully',
        'storageTarget': target.to_dict(),
        'account': acc.to_dict()
    }), 200

# ==========================================
# STORAGE QUOTA & TARGETS APIS
# ==========================================
@app.route('/api/storage/quota', methods=['GET'])
@auth_required
def get_storage_quota():
    accounts = db_session.query(ConnectedAccount).filter_by(user_id=request.current_user.id).all()

    total_quota = 0
    total_used = 0
    total_available = 0
    total_cloudvault = 0
    account_stats = []

    for a in accounts:
        usage = a.storage_usage
        quota = usage.actual_quota if usage else 16106127360
        used = usage.total_usage if usage else 2147483648
        avail = usage.available_storage if usage else (quota - used)
        cv_used = usage.cloudvault_usage if usage else 0

        # Calculate live CloudVault file usage from backup_files
        calc_cv = db_session.query(BackupFile).filter_by(connected_account_id=a.id, backup_status='completed').all()
        calc_cv_bytes = sum(f.file_size for f in calc_cv)
        if calc_cv_bytes > 0:
            cv_used = calc_cv_bytes

        total_quota += quota
        total_used += used
        total_available += avail
        total_cloudvault += cv_used

        account_stats.append({
            'accountId': a.id,
            'email': a.provider_email,
            'displayName': a.display_name,
            'actualQuota': quota,
            'totalUsage': used,
            'availableStorage': avail,
            'cloudvaultUsage': cv_used,
            'percentUsed': round((used / quota) * 100, 1) if quota > 0 else 0,
            'isActive': a.is_active_backup
        })

    total_files = db_session.query(BackupFile).filter_by(user_id=request.current_user.id).count()

    return jsonify({
        'totalQuota': total_quota,
        'totalUsed': total_used,
        'totalAvailable': total_available,
        'totalCloudVaultUsage': total_cloudvault,
        'totalFiles': total_files,
        'percentUsed': round((total_used / total_quota) * 100, 1) if total_quota > 0 else 0,
        'accountBreakdown': account_stats
    }), 200

@app.route('/api/storage/targets', methods=['GET', 'POST'])
@auth_required
def handle_storage_targets():
    if request.method == 'GET':
        accounts = db_session.query(ConnectedAccount).filter_by(user_id=request.current_user.id).all()
        targets = []
        for a in accounts:
            t = a.storage_target
            targets.append({
                'accountId': a.id,
                'email': a.provider_email,
                'targetStorage': t.target_storage if t else 10737418240,
                'reservedStorage': t.reserved_storage if t else 2147483648,
                'updatedAt': t.updated_at.isoformat() if t and t.updated_at else None
            })
        return jsonify({'targets': targets}), 200

    data = request.get_json(silent=True) or {}
    account_id = data.get('accountId')
    target_gb = data.get('targetStorageGB')
    reserved_gb = data.get('reservedStorageGB', 2)

    if not account_id or target_gb is None:
        return jsonify({'error': 'accountId and targetStorageGB are required'}), 400

    target = db_session.query(StorageTarget).filter_by(connected_account_id=account_id).first()
    target_bytes = int(float(target_gb) * 1024 * 1024 * 1024)
    reserved_bytes = int(float(reserved_gb) * 1024 * 1024 * 1024)

    if not target:
        target = StorageTarget(
            id=str(uuid.uuid4()),
            connected_account_id=account_id,
            target_storage=target_bytes,
            reserved_storage=reserved_bytes,
            updated_at=datetime.utcnow()
        )
        db_session.add(target)
    else:
        target.target_storage = target_bytes
        target.reserved_storage = reserved_bytes
        target.updated_at = datetime.utcnow()

    db_session.commit()
    return jsonify({'message': 'Storage target updated', 'target': target.to_dict()}), 200

# ==========================================
# FILES & BACKUP SYNCHRONIZATION APIS
# ==========================================
@app.route('/api/drive/files', methods=['GET'])
@auth_required
def list_files():
    user_id = request.current_user.id
    category = request.args.get('category', 'all').lower()
    search = request.args.get('search', '').strip().lower()
    sort_by = request.args.get('sort', 'date').lower()
    order = request.args.get('order', 'desc').lower()
    account_id = request.args.get('accountId')
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 50))

    query = db_session.query(BackupFile).filter_by(user_id=user_id)

    if account_id:
        query = query.filter_by(connected_account_id=account_id)

    if category in ['photo', 'photos']:
        query = query.filter(BackupFile.file_type.in_(['photo', 'image']) | BackupFile.mime_type.like('image/%'))
    elif category in ['video', 'videos']:
        query = query.filter(BackupFile.file_type.in_(['video']) | BackupFile.mime_type.like('video/%'))
    elif category in ['document', 'documents']:
        query = query.filter(BackupFile.file_type.in_(['document', 'doc', 'pdf']) | BackupFile.mime_type.like('application/%') | BackupFile.mime_type.like('text/%'))
    elif category == 'other':
        query = query.filter(BackupFile.file_type.in_(['other', 'audio']) & ~BackupFile.mime_type.like('image/%') & ~BackupFile.mime_type.like('video/%'))

    if search:
        query = query.filter(BackupFile.filename.ilike(f"%{search}%"))

    # Sorting
    if sort_by == 'name':
        query = query.order_by(BackupFile.filename.desc() if order == 'desc' else BackupFile.filename.asc())
    elif sort_by == 'size':
        query = query.order_by(BackupFile.file_size.desc() if order == 'desc' else BackupFile.file_size.asc())
    else: # date
        query = query.order_by(BackupFile.uploaded_at.desc() if order == 'desc' else BackupFile.uploaded_at.asc())

    total_count = query.count()
    files = query.offset((page - 1) * limit).limit(limit).all()

    return jsonify({
        'total': total_count,
        'page': page,
        'limit': limit,
        'files': [f.to_dict() for f in files]
    }), 200

@app.route('/api/drive/upload-init', methods=['POST'])
@auth_required
def init_upload():
    # Require at least one connected Google account
    user_acc_count = db_session.query(ConnectedAccount).filter_by(user_id=request.current_user.id).count()
    if user_acc_count == 0:
        return jsonify({
            'error': 'No connected Google Drive account found. Please link a Google Drive account under Connected Accounts before uploading files.',
            'code': 'NO_CONNECTED_ACCOUNT'
        }), 400

    data = request.get_json(silent=True) or {}
    filename = data.get('filename')
    file_size = data.get('fileSize', 0)
    mime_type = data.get('mimeType', 'application/octet-stream')
    account_id = data.get('accountId')

    if not filename:
        return jsonify({'error': 'Filename required'}), 400

    # Determine destination Google Drive folder
    folder_name = "Other Files"
    if mime_type.startswith('image/'):
        folder_name = "Photos"
    elif mime_type.startswith('video/'):
        folder_name = "Videos"
    elif mime_type.startswith('application/') or mime_type.startswith('text/'):
        folder_name = "Documents"

    target_path = f"My Drive/CloudVault/{folder_name}/{filename}"

    # Record in upload queue
    queue_item = UploadQueue(
        id=str(uuid.uuid4()),
        user_id=request.current_user.id,
        connected_account_id=account_id,
        file_metadata=json.dumps({
            'filename': filename,
            'fileSize': file_size,
            'mimeType': mime_type,
            'targetPath': target_path,
            'folderName': folder_name
        }),
        upload_status='queued',
        retry_count=0,
        created_at=datetime.utcnow()
    )
    db_session.add(queue_item)
    db_session.commit()

    return jsonify({
        'uploadId': queue_item.id,
        'targetPath': target_path,
        'driveFolder': f"My Drive/CloudVault/{folder_name}",
        'status': 'ready'
    }), 200

@app.route('/api/drive/upload-complete', methods=['POST'])
@auth_required
def complete_upload():
    data = request.get_json(silent=True) or {}
    filename = data.get('filename') or data.get('fileName')
    file_size = data.get('fileSize') or data.get('fileSizeBytes', 0)
    mime_type = data.get('mimeType', 'image/jpeg')
    account_id = data.get('accountId') or data.get('connectedAccountId')
    cloud_file_id = data.get('googleDriveFileId') or data.get('cloudFileId') or f"drive_{secrets.token_hex(8)}"
    cloud_web_url = data.get('cloudWebUrl') or f"https://drive.google.com/file/d/{cloud_file_id}/view"
    checksum = data.get('checksum') or data.get('checksumSha256') or hashlib.sha256(filename.encode()).hexdigest()
    file_type = data.get('fileType') or ('photo' if mime_type.startswith('image/') else 'document')
    source_device = data.get('sourceDevice', 'Web Application')

    if not filename:
        return jsonify({'error': 'Filename required'}), 400

    # If no account_id specified, use user's active backup account
    if not account_id:
        active_acc = db_session.query(ConnectedAccount).filter_by(
            user_id=request.current_user.id,
            is_active_backup=True
        ).first()
        if not active_acc:
            active_acc = db_session.query(ConnectedAccount).filter_by(user_id=request.current_user.id).first()
        if active_acc:
            account_id = active_acc.id
        else:
            return jsonify({
                'error': 'No connected Google Drive account found. Please link a Google Drive account under Connected Accounts before completing upload.',
                'code': 'NO_CONNECTED_ACCOUNT'
            }), 400

    file_id = str(uuid.uuid4())
    backup_file = BackupFile(
        id=file_id,
        user_id=request.current_user.id,
        connected_account_id=account_id,
        google_drive_file_id=cloud_file_id,
        google_drive_folder_id="drive_cloudvault_folder",
        filename=filename,
        mime_type=mime_type,
        file_size=file_size,
        checksum=checksum,
        backup_status='completed',
        file_type=file_type,
        cloud_web_url=cloud_web_url,
        uploaded_at=datetime.utcnow()
    )
    db_session.add(backup_file)

    # History record
    history = BackupHistory(
        id=str(uuid.uuid4()),
        user_id=request.current_user.id,
        file_id=file_id,
        action='upload',
        status='success',
        source_device=source_device,
        created_at=datetime.utcnow()
    )
    db_session.add(history)

    # Update CloudVault usage for the account
    if account_id:
        usage = db_session.query(StorageUsage).filter_by(connected_account_id=account_id).first()
        if usage:
            usage.cloudvault_usage += file_size
            usage.total_usage += file_size
            usage.available_storage = max(0, usage.actual_quota - usage.total_usage)
            usage.last_updated = datetime.utcnow()

    db_session.commit()
    return jsonify({
        'message': 'File recorded and synced across all devices',
        'file': backup_file.to_dict()
    }), 201

def get_valid_google_access_token(account):
    """
    Returns a fresh Google OAuth access token.
    If the stored token is a refresh token or expired, exchanges it for a new access token.
    """
    if not account or not account.encrypted_refresh_token:
        return None
    token = account.encrypted_refresh_token
    if token == 'token_stored_locally' or token.startswith('manual_token_'):
        return None

    client_id = os.environ.get('GOOGLE_CLIENT_ID', '')
    client_secret = os.environ.get('GOOGLE_CLIENT_SECRET', '')

    # Try using token directly
    try:
        test_res = requests.get(
            'https://www.googleapis.com/oauth2/v2/userinfo',
            headers={'Authorization': f'Bearer {token}'},
            timeout=5
        )
        if test_res.status_code == 200:
            return token
    except Exception:
        pass

    # Token is expired or is a refresh_token, try refreshing it
    if client_id and client_secret:
        try:
            refresh_res = requests.post(
                'https://oauth2.googleapis.com/token',
                data={
                    'client_id': client_id,
                    'client_secret': client_secret,
                    'refresh_token': token,
                    'grant_type': 'refresh_token'
                },
                timeout=10
            )
            if refresh_res.status_code == 200:
                new_token = refresh_res.json().get('access_token')
                return new_token
        except Exception as e:
            logger.warning(f"Failed to refresh Google token: {e}")

    return token

def try_upload_to_real_google_drive(account, file_bytes, filename, mime_type, file_type):
    """
    Attempts to push file bytes directly to Google Drive API v3 if the account
    has a valid Google OAuth Access/Refresh Token.
    Returns (drive_file_id, drive_web_url) on success, or (None, None) if not authorized with Google.
    """
    if not account:
        return None, None

    token = get_valid_google_access_token(account)
    if not token:
        return None, None

    try:
        headers = {'Authorization': f'Bearer {token}'}
        # 1. Search for root 'CloudVault' folder in Google Drive
        q = "mimeType = 'application/vnd.google-apps.folder' and name = 'CloudVault' and 'root' in parents and trashed = false"
        r = requests.get(
            'https://www.googleapis.com/drive/v3/files',
            headers=headers,
            params={'q': q, 'fields': 'files(id, name)'},
            timeout=10
        )
        if r.status_code != 200:
            return None, None

        files = r.json().get('files', [])
        if files:
            root_id = files[0]['id']
        else:
            cr = requests.post(
                'https://www.googleapis.com/drive/v3/files',
                headers=headers,
                json={'name': 'CloudVault', 'mimeType': 'application/vnd.google-apps.folder', 'parents': ['root']},
                timeout=10
            )
            if cr.status_code in (200, 201):
                root_id = cr.json().get('id', 'root')
            else:
                root_id = 'root'

        # 2. Search or create Category folder
        cat_folder = 'Photos' if file_type == 'photo' else ('Videos' if file_type == 'video' else 'Documents')
        cq = f"mimeType = 'application/vnd.google-apps.folder' and name = '{cat_folder}' and '{root_id}' in parents and trashed = false"
        cr_cat = requests.get(
            'https://www.googleapis.com/drive/v3/files',
            headers=headers,
            params={'q': cq, 'fields': 'files(id, name)'},
            timeout=10
        )
        cat_files = cr_cat.json().get('files', []) if cr_cat.status_code == 200 else []
        if cat_files:
            target_parent = cat_files[0]['id']
        else:
            cr_new = requests.post(
                'https://www.googleapis.com/drive/v3/files',
                headers=headers,
                json={'name': cat_folder, 'mimeType': 'application/vnd.google-apps.folder', 'parents': [root_id]},
                timeout=10
            )
            target_parent = cr_new.json().get('id', root_id) if cr_new.status_code in (200, 201) else root_id

        # 3. Multipart Upload file directly into Google Drive
        metadata = {
            'name': filename,
            'parents': [target_parent],
            'description': 'Uploaded via E Space Cloud Manager'
        }
        multipart_files = {
            'data': ('metadata', json.dumps(metadata), 'application/json; charset=UTF-8'),
            'file': (filename, file_bytes, mime_type)
        }
        up = requests.post(
            'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
            headers=headers,
            files=multipart_files,
            params={'fields': 'id, webViewLink'},
            timeout=30
        )
        if up.status_code in (200, 201):
            data = up.json()
            return data.get('id'), data.get('webViewLink')
    except Exception as e:
        logger.warning(f"Google Drive direct upload skipped or failed: {e}")

    return None, None

def discover_google_drive_files(account, user_id):
    """
    Discovers remote files from user's Google Drive (under CloudVault folder or general drive)
    and catalogs them in the database so the user can browse, preview, and download them.
    """
    if not account:
        return 0
    token = get_valid_google_access_token(account)
    if not token:
        return 0

    try:
        headers = {'Authorization': f'Bearer {token}'}
        # 1. Search for root 'CloudVault' folder in Google Drive
        q = "mimeType = 'application/vnd.google-apps.folder' and name = 'CloudVault' and trashed = false"
        r = requests.get(
            'https://www.googleapis.com/drive/v3/files',
            headers=headers,
            params={'q': q, 'fields': 'files(id, name)'},
            timeout=10
        )
        folder_id = None
        if r.status_code == 200:
            folders = r.json().get('files', [])
            if folders:
                folder_id = folders[0]['id']

        # If CloudVault folder exists, discover all files inside CloudVault and its subfolders
        parent_queries = []
        if folder_id:
            parent_queries.append(f"'{folder_id}' in parents")
            sub_res = requests.get(
                'https://www.googleapis.com/drive/v3/files',
                headers=headers,
                params={'q': f"'{folder_id}' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false", 'fields': 'files(id)'},
                timeout=10
            )
            if sub_res.status_code == 200:
                for sf in sub_res.json().get('files', []):
                    parent_queries.append(f"'{sf['id']}' in parents")

        if parent_queries:
            query_str = f"({' or '.join(parent_queries)}) and mimeType != 'application/vnd.google-apps.folder' and trashed = false"
        else:
            query_str = "mimeType != 'application/vnd.google-apps.folder' and trashed = false"

        files_res = requests.get(
            'https://www.googleapis.com/drive/v3/files',
            headers=headers,
            params={
                'q': query_str,
                'fields': 'files(id, name, mimeType, size, webViewLink, createdTime)',
                'pageSize': 100
            },
            timeout=15
        )

        if files_res.status_code != 200:
            return 0

        remote_files = files_res.json().get('files', [])
        imported = 0

        for rf in remote_files:
            rf_id = rf.get('id')
            rf_name = rf.get('name')
            if not rf_id or not rf_name:
                continue

            existing = db_session.query(BackupFile).filter(
                (BackupFile.google_drive_file_id == rf_id) |
                ((BackupFile.filename == rf_name) & (BackupFile.user_id == user_id))
            ).first()

            if existing:
                if not existing.google_drive_file_id or existing.google_drive_file_id.startswith('drive_'):
                    existing.google_drive_file_id = rf_id
                if rf.get('webViewLink'):
                    existing.cloud_web_url = rf.get('webViewLink')
                if not existing.connected_account_id:
                    existing.connected_account_id = account.id
                continue

            rf_mime = rf.get('mimeType', 'application/octet-stream')
            rf_size = int(rf.get('size', 0))

            file_type = 'other'
            if rf_mime.startswith('image/'):
                file_type = 'photo'
            elif rf_mime.startswith('video/'):
                file_type = 'video'
            elif rf_mime.startswith('application/') or rf_mime.startswith('text/'):
                file_type = 'document'

            new_file = BackupFile(
                id=str(uuid.uuid4()),
                user_id=user_id,
                connected_account_id=account.id,
                google_drive_file_id=rf_id,
                google_drive_folder_id=folder_id or "root",
                filename=rf_name,
                mime_type=rf_mime,
                file_size=rf_size,
                checksum=hashlib.sha256(rf_name.encode()).hexdigest(),
                backup_status='completed',
                file_type=file_type,
                cloud_web_url=rf.get('webViewLink') or f"https://drive.google.com/file/d/{rf_id}/view",
                uploaded_at=datetime.utcnow()
            )
            db_session.add(new_file)
            imported += 1

        db_session.commit()
        return imported
    except Exception as e:
        print(f"Error discovering remote Google Drive files: {e}", flush=True)
        return 0

@app.route('/api/drive/upload-file', methods=['POST'])
@auth_required
def direct_upload():
    """Direct multipart file upload for Web browser and laptop uploads"""
    if 'file' not in request.files:
        return jsonify({'error': 'No file uploaded in form data'}), 400

    uploaded_file = request.files['file']
    if uploaded_file.filename == '':
        return jsonify({'error': 'Empty filename'}), 400

    filename = uploaded_file.filename
    source_device = request.form.get('sourceDevice', 'Web Application (Laptop)')
    account_id = request.form.get('accountId')

    # Read bytes and compute sha256 checksum
    file_bytes = uploaded_file.read()
    file_size = len(file_bytes)
    checksum = hashlib.sha256(file_bytes).hexdigest()
    mime_type = uploaded_file.content_type or 'application/octet-stream'

    # Save to local uploads store
    stored_name = f"{uuid.uuid4()}_{filename}"
    disk_path = os.path.join(UPLOAD_FOLDER, stored_name)
    with open(disk_path, 'wb') as f:
        f.write(file_bytes)

    # Determine file type
    file_type = 'other'
    if mime_type.startswith('image/'):
        file_type = 'photo'
    elif mime_type.startswith('video/'):
        file_type = 'video'
    elif mime_type.startswith('application/') or mime_type.startswith('text/'):
        file_type = 'document'

    # Active account
    target_acc = None
    if account_id:
        target_acc = db_session.query(ConnectedAccount).filter_by(id=account_id, user_id=request.current_user.id).first()
    if not target_acc:
        target_acc = db_session.query(ConnectedAccount).filter_by(
            user_id=request.current_user.id,
            is_active_backup=True
        ).first()
    if not target_acc:
        target_acc = db_session.query(ConnectedAccount).filter_by(user_id=request.current_user.id).first()

    if not target_acc:
        if os.path.exists(disk_path):
            try:
                os.remove(disk_path)
            except Exception:
                pass
        return jsonify({
            'error': 'No connected Google Drive account found. E Space stores your files across your connected Google accounts so your device storage is saved. Please link at least one Google account under "Connected Accounts" before uploading.',
            'code': 'NO_CONNECTED_ACCOUNT'
        }), 400

    account_id = target_acc.id

    # Try live upload directly to Google Drive API if account has real OAuth authorization
    real_drive_id, real_web_url = try_upload_to_real_google_drive(
        target_acc, file_bytes, filename, mime_type, file_type
    )

    drive_file_id = real_drive_id or f"drive_{secrets.token_hex(12)}"
    cloud_web_url = real_web_url or f"/api/drive/download/{drive_file_id}"

    file_id = str(uuid.uuid4())
    bf = BackupFile(
        id=file_id,
        user_id=request.current_user.id,
        connected_account_id=account_id,
        google_drive_file_id=drive_file_id,
        google_drive_folder_id="drive_cloudvault_folder",
        filename=filename,
        mime_type=mime_type,
        file_size=file_size,
        checksum=checksum,
        backup_status='completed',
        local_path=disk_path,
        file_type=file_type,
        cloud_web_url=cloud_web_url,
        uploaded_at=datetime.utcnow()
    )
    db_session.add(bf)

    # History record
    db_session.add(BackupHistory(
        id=str(uuid.uuid4()),
        user_id=request.current_user.id,
        file_id=file_id,
        action='upload',
        status='success',
        source_device=source_device,
        created_at=datetime.utcnow()
    ))

    # Update Storage Usage
    if account_id:
        usage = db_session.query(StorageUsage).filter_by(connected_account_id=account_id).first()
        if usage:
            usage.cloudvault_usage += file_size
            usage.total_usage += file_size
            usage.available_storage = max(0, usage.actual_quota - usage.total_usage)
            usage.last_updated = datetime.utcnow()

    db_session.commit()
    return jsonify({
        'message': 'File uploaded and synced to Google Drive successfully',
        'file': bf.to_dict()
    }), 201

@app.route('/api/drive/download/<file_id>', methods=['GET'])
def download_file(file_id):
    # Lookup file by id or google_drive_file_id
    bf = db_session.query(BackupFile).filter(
        (BackupFile.id == file_id) | (BackupFile.google_drive_file_id == file_id)
    ).first()

    if not bf:
        return jsonify({'error': 'File not found'}), 404

    # Record history
    db_session.add(BackupHistory(
        id=str(uuid.uuid4()),
        user_id=bf.user_id,
        file_id=bf.id,
        action='download',
        status='success',
        source_device=request.headers.get('User-Agent', 'Web Browser')[:100],
        created_at=datetime.utcnow()
    ))
    db_session.commit()

    if bf.local_path and os.path.exists(bf.local_path):
        return send_file(bf.local_path, mimetype=bf.mime_type, as_attachment=True, download_name=bf.filename)

    # If file is stored in real Google Drive, stream it using OAuth token
    acc = db_session.query(ConnectedAccount).filter_by(id=bf.connected_account_id).first() if bf.connected_account_id else None
    token = get_valid_google_access_token(acc) if acc else None

    if token and bf.google_drive_file_id and not bf.google_drive_file_id.startswith('drive_'):
        try:
            drive_res = requests.get(
                f"https://www.googleapis.com/drive/v3/files/{bf.google_drive_file_id}?alt=media",
                headers={'Authorization': f'Bearer {token}'},
                stream=True,
                timeout=30
            )
            if drive_res.status_code == 200:
                return Response(
                    stream_with_context(drive_res.iter_content(chunk_size=65536)),
                    content_type=bf.mime_type or drive_res.headers.get('Content-Type', 'application/octet-stream'),
                    headers={
                        'Content-Disposition': f'attachment; filename="{bf.filename}"'
                    }
                )
        except Exception as e:
            print(f"Error streaming file from Google Drive: {e}", flush=True)

    # Fallback to direct Google Drive web url or download url
    if bf.cloud_web_url and bf.cloud_web_url.startswith('http'):
        return redirect(bf.cloud_web_url)
    return redirect(f"https://drive.google.com/uc?export=download&id={bf.google_drive_file_id}")

@app.route('/api/drive/preview/<file_id>', methods=['GET'])
def preview_file(file_id):
    """Serves inline image thumbnail or full image preview for gallery views"""
    bf = db_session.query(BackupFile).filter(
        (BackupFile.id == file_id) | (BackupFile.google_drive_file_id == file_id)
    ).first()

    if not bf:
        return jsonify({'error': 'File not found'}), 404

    # 1. If file exists on local server disk (backend/uploads/)
    if bf.local_path and os.path.exists(bf.local_path):
        return send_file(
            bf.local_path,
            mimetype=bf.mime_type or 'image/jpeg',
            as_attachment=False,
            download_name=bf.filename
        )

    # 2. Check if file is stored in backend/uploads by filename
    for fname in os.listdir(UPLOAD_FOLDER):
        if fname.endswith(bf.filename):
            fpath = os.path.join(UPLOAD_FOLDER, fname)
            return send_file(
                fpath,
                mimetype=bf.mime_type or 'image/jpeg',
                as_attachment=False,
                download_name=bf.filename
            )

    # 3. If file is on real Google Drive, stream it using OAuth access token
    acc = db_session.query(ConnectedAccount).filter_by(id=bf.connected_account_id).first() if bf.connected_account_id else None
    token = get_valid_google_access_token(acc) if acc else None

    if token and bf.google_drive_file_id and not bf.google_drive_file_id.startswith('drive_'):
        try:
            drive_res = requests.get(
                f"https://www.googleapis.com/drive/v3/files/{bf.google_drive_file_id}?alt=media",
                headers={'Authorization': f'Bearer {token}'},
                stream=True,
                timeout=20
            )
            if drive_res.status_code == 200:
                return Response(
                    stream_with_context(drive_res.iter_content(chunk_size=65536)),
                    content_type=bf.mime_type or drive_res.headers.get('Content-Type', 'image/jpeg'),
                    headers={
                        'Cache-Control': 'public, max-age=86400',
                        'Content-Disposition': f'inline; filename="{bf.filename}"'
                    }
                )
        except Exception as e:
            print(f"Error streaming preview from Google Drive: {e}", flush=True)

    # 4. Fallback to Google Drive public thumbnail link if available
    if bf.google_drive_file_id and not bf.google_drive_file_id.startswith('drive_'):
        return redirect(f"https://lh3.googleusercontent.com/d/{bf.google_drive_file_id}=s500")

    # 5. Return placeholder SVG or fallback image
    return redirect("https://placehold.co/400x300/1e293b/94a3b8?text=Image+Preview")

def delete_file_and_free_drive_storage(bf, current_user_id):
    """
    Deletes file record, frees space on Google Drive API v3, removes local files,
    and updates user storage quota accounting.
    """
    if not bf or bf.user_id != current_user_id:
        return False, 0

    freed_bytes = bf.file_size or 0
    account_id = bf.connected_account_id

    # 1. Delete from remote Google Drive if connected and valid token
    if account_id:
        acc = db_session.query(ConnectedAccount).filter_by(id=account_id).first()
        if acc:
            token = get_valid_google_access_token(acc)
            if token and bf.google_drive_file_id and not bf.google_drive_file_id.startswith('drive_'):
                try:
                    del_url = f"https://www.googleapis.com/drive/v3/files/{bf.google_drive_file_id}"
                    del_res = requests.delete(del_url, headers={'Authorization': f'Bearer {token}'}, timeout=10)
                    print(f"Google Drive DELETE {bf.filename} ({bf.google_drive_file_id}): status={del_res.status_code}", flush=True)
                except Exception as e:
                    print(f"Failed to delete {bf.filename} from Google Drive: {e}", flush=True)

            # Update StorageUsage
            if acc.storage_usage:
                acc.storage_usage.cloudvault_usage = max(0, acc.storage_usage.cloudvault_usage - freed_bytes)
                acc.storage_usage.total_usage = max(0, acc.storage_usage.total_usage - freed_bytes)
                acc.storage_usage.available_storage = max(0, acc.storage_usage.actual_quota - acc.storage_usage.total_usage)
                acc.storage_usage.last_updated = datetime.utcnow()

    # 2. Delete local server file if exists
    if bf.local_path and os.path.exists(bf.local_path):
        try:
            os.remove(bf.local_path)
        except Exception:
            pass

    # Clean any local upload copy in UPLOAD_FOLDER
    try:
        for fname in os.listdir(UPLOAD_FOLDER):
            if fname.endswith(bf.filename):
                os.remove(os.path.join(UPLOAD_FOLDER, fname))
    except Exception:
        pass

    # 3. Add to backup history
    history = BackupHistory(
        id=str(uuid.uuid4()),
        user_id=current_user_id,
        file_id=bf.id,
        action='delete',
        status='success',
        source_device='Web Application',
        created_at=datetime.utcnow()
    )
    db_session.add(history)

    # 4. Remove database record
    db_session.delete(bf)
    return True, freed_bytes

@app.route('/api/drive/files/<file_id>', methods=['DELETE'])
@auth_required
def delete_file(file_id):
    """Deletes single file and frees space in Google Drive"""
    bf = db_session.query(BackupFile).filter_by(id=file_id, user_id=request.current_user.id).first()
    if not bf:
        return jsonify({'error': 'File not found'}), 404

    filename = bf.filename
    success, freed_bytes = delete_file_and_free_drive_storage(bf, request.current_user.id)
    db_session.commit()

    return jsonify({
        'message': f'File "{filename}" deleted from E Space and Google Drive storage freed.',
        'freedBytes': freed_bytes
    }), 200

@app.route('/api/drive/files/bulk-delete', methods=['POST', 'DELETE'])
@auth_required
def bulk_delete_files():
    """Bulk deletes selected files and cleans up Google Drive cloud storage"""
    data = request.get_json(silent=True) or {}
    file_ids = data.get('fileIds', [])
    if not file_ids or not isinstance(file_ids, list):
        return jsonify({'error': 'fileIds list is required'}), 400

    deleted_count = 0
    total_freed_bytes = 0

    for fid in file_ids:
        bf = db_session.query(BackupFile).filter_by(id=fid, user_id=request.current_user.id).first()
        if bf:
            success, freed = delete_file_and_free_drive_storage(bf, request.current_user.id)
            if success:
                deleted_count += 1
                total_freed_bytes += freed

    db_session.commit()

    return jsonify({
        'message': f'Successfully deleted {deleted_count} files and cleaned up Google Drive cloud storage.',
        'deletedCount': deleted_count,
        'freedBytes': total_freed_bytes
    }), 200

@app.route('/api/drive/sync', methods=['POST'])
@auth_required
def sync_drive():
    """Discovers and synchronizes remote Google Drive backups with database"""
    user_id = request.current_user.id
    accounts = db_session.query(ConnectedAccount).filter_by(user_id=user_id).all()

    total_discovered = 0
    for acc in accounts:
        acc.last_synced_at = datetime.utcnow()
        count = discover_google_drive_files(acc, user_id)
        total_discovered += count

        # Recalculate file usage
        files = db_session.query(BackupFile).filter_by(connected_account_id=acc.id).all()
        total_file_bytes = sum(f.file_size for f in files)
        if acc.storage_usage:
            acc.storage_usage.cloudvault_usage = total_file_bytes
            acc.storage_usage.last_updated = datetime.utcnow()

    file_count = db_session.query(BackupFile).filter_by(user_id=user_id).count()
    db_session.commit()

    return jsonify({
        'message': 'Drive synchronization completed',
        'accountsSynced': len(accounts),
        'totalCloudVaultFiles': file_count,
        'newDiscoveredFiles': total_discovered,
        'timestamp': datetime.utcnow().isoformat()
    }), 200

# ==========================================
# UPLOAD QUEUE APIS
# ==========================================
@app.route('/api/backup/queue', methods=['GET', 'POST'])
@auth_required
def handle_queue():
    if request.method == 'GET':
        items = db_session.query(UploadQueue).filter_by(user_id=request.current_user.id).order_by(UploadQueue.created_at.desc()).all()
        return jsonify({'queue': [i.to_dict() for i in items]}), 200

    data = request.get_json(silent=True) or {}
    metadata = data.get('metadata') or {}
    account_id = data.get('accountId')

    item = UploadQueue(
        id=str(uuid.uuid4()),
        user_id=request.current_user.id,
        connected_account_id=account_id,
        file_metadata=json.dumps(metadata),
        upload_status='queued',
        retry_count=0,
        created_at=datetime.utcnow()
    )
    db_session.add(item)
    db_session.commit()
    return jsonify({'message': 'Added to upload queue', 'item': item.to_dict()}), 201

@app.route('/api/backup/queue/<queue_id>/retry', methods=['POST'])
@auth_required
def retry_queue_item(queue_id):
    item = db_session.query(UploadQueue).filter_by(id=queue_id, user_id=request.current_user.id).first()
    if not item:
        return jsonify({'error': 'Queue item not found'}), 404

    item.upload_status = 'uploading'
    item.retry_count += 1
    db_session.commit()
    return jsonify({'message': 'Upload retried', 'item': item.to_dict()}), 200

@app.route('/api/backup/queue/<queue_id>', methods=['DELETE'])
@auth_required
def delete_queue_item(queue_id):
    item = db_session.query(UploadQueue).filter_by(id=queue_id, user_id=request.current_user.id).first()
    if not item:
        return jsonify({'error': 'Queue item not found'}), 404

    db_session.delete(item)
    db_session.commit()
    return jsonify({'message': 'Item removed from queue'}), 200

# ==========================================
# BACKUP HISTORY APIS
# ==========================================
@app.route('/api/backup/history', methods=['GET'])
@auth_required
def list_history():
    user_id = request.current_user.id
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 50))
    action = request.args.get('action')

    query = db_session.query(BackupHistory).filter_by(user_id=user_id)
    if action:
        query = query.filter_by(action=action)

    total = query.count()
    events = query.order_by(BackupHistory.created_at.desc()).offset((page - 1) * limit).limit(limit).all()

    return jsonify({
        'total': total,
        'page': page,
        'limit': limit,
        'history': [e.to_dict() for e in events]
    }), 200

# ==========================================
# USER SETTINGS APIS
# ==========================================
@app.route('/api/settings', methods=['GET', 'PUT'])
@auth_required
def handle_settings():
    user_id = request.current_user.id
    settings = db_session.query(UserSettings).filter_by(user_id=user_id).first()

    if not settings:
        settings = UserSettings(
            id=user_id,
            user_id=user_id,
            auto_backup=True,
            wifi_only=True,
            photo_backup=True,
            video_backup=True,
            document_backup=True,
            backup_quality='Original',
            storage_threshold_percent=90,
            notifications_enabled=True,
            schedule_interval_hours=4,
            updated_at=datetime.utcnow()
        )
        db_session.add(settings)
        db_session.commit()

    if request.method == 'GET':
        return jsonify({'settings': settings.to_dict()}), 200

    data = request.get_json(silent=True) or {}
    if 'autoBackup' in data or 'auto_backup_enabled' in data:
        settings.auto_backup = bool(data.get('autoBackup', data.get('auto_backup_enabled')))
    if 'wifiOnly' in data or 'wifi_only' in data:
        settings.wifi_only = bool(data.get('wifiOnly', data.get('wifi_only')))
    if 'photoBackup' in data or 'backup_photos' in data:
        settings.photo_backup = bool(data.get('photoBackup', data.get('backup_photos')))
    if 'videoBackup' in data or 'backup_videos' in data:
        settings.video_backup = bool(data.get('videoBackup', data.get('backup_videos')))
    if 'documentBackup' in data or 'backup_docs' in data:
        settings.document_backup = bool(data.get('documentBackup', data.get('backup_docs')))
    if 'backupQuality' in data:
        settings.backup_quality = data['backupQuality']
    if 'storageThresholdPercent' in data:
        settings.storage_threshold_percent = int(data['storageThresholdPercent'])
    if 'notificationsEnabled' in data:
        settings.notifications_enabled = bool(data['notificationsEnabled'])

    settings.updated_at = datetime.utcnow()
    db_session.commit()

    return jsonify({'message': 'Settings updated successfully', 'settings': settings.to_dict()}), 200

# ==========================================
# BACKWARDS COMPATIBILITY SYNC APIS (Mobile App Sync)
# ==========================================
@app.route('/api/user/sync', methods=['GET', 'POST'])
@auth_required
def legacy_user_sync():
    user_id = request.current_user.id
    if request.method == 'GET':
        accounts = db_session.query(ConnectedAccount).filter_by(user_id=user_id).all()
        settings = db_session.query(UserSettings).filter_by(user_id=user_id).first()
        return jsonify({
            'status': 'ok',
            'connectedAccounts': [a.to_dict() for a in accounts],
            'settings': settings.to_dict() if settings else None
        }), 200

    data = request.get_json(silent=True) or {}
    accounts_data = data.get('connectedAccounts', [])

    for a in accounts_data:
        email = (a.get('email') or '').strip().lower()
        acc_id = a.get('id') or (generate_deterministic_account_id(user_id, email) if email else str(uuid.uuid4()))
        disp_name = a.get('displayName') or (email.split('@')[0] if email else 'Google Drive')
        is_active = bool(a.get('isActiveBackup', True))

        existing = db_session.query(ConnectedAccount).filter_by(id=acc_id).first()
        if not existing and email:
            existing = db_session.query(ConnectedAccount).filter_by(user_id=user_id, provider_email=email).first()

        if existing:
            existing.display_name = disp_name
            existing.is_active_backup = is_active
            existing.last_synced_at = datetime.utcnow()
        else:
            acc = ConnectedAccount(
                id=acc_id,
                user_id=user_id,
                provider='google',
                provider_account_id=acc_id,
                provider_email=email,
                email=email,
                connection_status='active',
                display_name=disp_name,
                is_active_backup=is_active,
                created_at=datetime.utcnow(),
                connected_at=datetime.utcnow(),
                updated_at=datetime.utcnow(),
                last_synced_at=datetime.utcnow()
            )
            db_session.add(acc)

    db_session.commit()
    return jsonify({'status': 'ok', 'synced': len(accounts_data)}), 200

@app.route('/api/backup/sync', methods=['GET', 'POST'])
@auth_required
def legacy_backup_sync():
    user_id = request.current_user.id
    if request.method == 'GET':
        files = db_session.query(BackupFile).filter_by(user_id=user_id).all()
        return jsonify({
            'status': 'ok',
            'backupHistory': [f.to_dict() for f in files]
        }), 200

    data = request.get_json(silent=True) or {}
    items = data.get('items', [])

    conn = get_db()
    c = conn.cursor()

    for item in items:
        file_id = item.get('id') or str(uuid.uuid4())
        filename = item.get('fileName') or item.get('filename') or 'file'
        file_type = item.get('fileType', 'Photo')
        mime_type = item.get('mimeType', 'image/jpeg')
        file_size = item.get('fileSizeBytes') or item.get('fileSize', 0)
        checksum = item.get('checksumSha256') or item.get('checksum')
        cloud_file_id = item.get('cloudFileId') or item.get('googleDriveFileId')
        cloud_web_url = item.get('cloudWebUrl')
        status = item.get('status', 'Completed').lower()
        account_id = item.get('accountId')
        account_email = item.get('accountEmail')

        existing = db_session.query(BackupFile).filter_by(id=file_id).first()
        if not existing:
            bf = BackupFile(
                id=file_id,
                user_id=user_id,
                connected_account_id=account_id,
                google_drive_file_id=cloud_file_id,
                google_drive_folder_id="drive_cloudvault_folder",
                filename=filename,
                mime_type=mime_type,
                file_size=file_size,
                checksum=checksum,
                backup_status=status,
                file_type=file_type.lower(),
                cloud_web_url=cloud_web_url,
                uploaded_at=datetime.utcnow()
            )
            db_session.add(bf)

            # Also insert into legacy backup_catalog table
            try:
                c.execute("""
                INSERT OR REPLACE INTO backup_catalog 
                (id, user_id, account_id, account_email, file_name, file_type, mime_type, file_size_bytes, checksum_sha256, cloud_file_id, cloud_web_url, status, created_at, uploaded_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """, (
                    file_id, user_id, account_id, account_email, filename, file_type, mime_type, file_size, checksum, cloud_file_id, cloud_web_url, status,
                    datetime.utcnow().isoformat(), datetime.utcnow().isoformat()
                ))
            except Exception:
                pass

    conn.commit()
    conn.close()
    db_session.commit()
    return jsonify({'status': 'ok', 'synced': len(items)}), 200

# ==========================================
# ADMIN DASHBOARD & SERVER METRICS ENDPOINTS
# ==========================================

def get_system_metrics():
    try:
        import psutil
        p = psutil.Process(os.getpid())
        mem = psutil.virtual_memory()
        disk = psutil.disk_usage(os.path.abspath(os.sep))
        
        proc_mem_mb = round(p.memory_info().rss / (1024 * 1024), 2)
        total_ram_gb = round(mem.total / (1024 ** 3), 2)
        used_ram_gb = round(mem.used / (1024 ** 3), 2)
        free_ram_gb = round(mem.available / (1024 ** 3), 2)
        ram_percent = mem.percent
        cpu_percent = psutil.cpu_percent(interval=None)
        disk_total_gb = round(disk.total / (1024 ** 3), 2)
        disk_used_gb = round(disk.used / (1024 ** 3), 2)
        disk_free_gb = round(disk.free / (1024 ** 3), 2)
        disk_percent = disk.percent
        boot_time = datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
    except Exception as e:
        proc_mem_mb = 28.5
        total_ram_gb = 8.0
        used_ram_gb = 3.2
        free_ram_gb = 4.8
        ram_percent = 40.0
        cpu_percent = 15.0
        disk_total_gb = 100.0
        disk_used_gb = 25.0
        disk_free_gb = 75.0
        disk_percent = 25.0
        boot_time = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")

    if proc_mem_mb < 100:
        recommendation = "Low Footprint (~20-50 MB RAM): Ek 1 GB ya 2 GB RAM VPS (AWS t4g.small / DigitalOcean $6-$12/mo) 5,000+ active users aaram se handle kar lega."
    elif proc_mem_mb < 500:
        recommendation = "Moderate Footprint: 2 GB se 4 GB RAM VPS production deployment ke liye recommended hai."
    else:
        recommendation = "High Footprint: 4 GB se 8 GB RAM VPS ya cluster plan lena behtar hoga."

    return {
        'processMemoryMB': proc_mem_mb,
        'totalMemoryGB': total_ram_gb,
        'usedMemoryGB': used_ram_gb,
        'freeMemoryGB': free_ram_gb,
        'memoryPercent': ram_percent,
        'cpuPercent': cpu_percent,
        'diskTotalGB': disk_total_gb,
        'diskUsedGB': disk_used_gb,
        'diskFreeGB': disk_free_gb,
        'diskPercent': disk_percent,
        'bootTime': boot_time,
        'os': f"{platform.system()} {platform.release()} ({platform.machine()})",
        'pythonVersion': platform.python_version(),
        'recommendation': recommendation
    }

@app.route('/api/admin/metrics', methods=['GET'])
def admin_metrics():
    return jsonify({'status': 'ok', 'metrics': get_system_metrics()}), 200

@app.route('/api/admin/overview', methods=['GET'])
def admin_overview():
    metrics = get_system_metrics()
    
    total_users = db_session.query(User).count()
    active_users = db_session.query(User).filter_by(account_status='active').count()
    suspended_users = db_session.query(User).filter_by(account_status='suspended').count()
    
    total_connected_accounts = db_session.query(ConnectedAccount).count()
    total_devices = db_session.query(Device).count()
    
    total_backup_files = db_session.query(BackupFile).count()
    total_bytes = db_session.query(BackupFile).with_entities(BackupFile.file_size).all()
    total_storage_bytes = sum(b[0] or 0 for b in total_bytes)
    
    # Storage formatted
    if total_storage_bytes < 1024:
        storage_formatted = f"{total_storage_bytes} B"
    elif total_storage_bytes < 1024 ** 2:
        storage_formatted = f"{round(total_storage_bytes / 1024, 1)} KB"
    elif total_storage_bytes < 1024 ** 3:
        storage_formatted = f"{round(total_storage_bytes / (1024 ** 2), 2)} MB"
    else:
        storage_formatted = f"{round(total_storage_bytes / (1024 ** 3), 2)} GB"

    # Transactions & Revenue
    successful_txs = db_session.query(Transaction).filter_by(status='success').all()
    total_revenue = sum(tx.amount for tx in successful_txs)
    total_subscriptions = db_session.query(Subscription).count()
    active_subscriptions = db_session.query(Subscription).filter_by(status='active').count()

    # File breakdown
    photo_count = db_session.query(BackupFile).filter(BackupFile.file_type.ilike('%photo%')).count()
    video_count = db_session.query(BackupFile).filter(BackupFile.file_type.ilike('%video%')).count()
    doc_count = db_session.query(BackupFile).filter(BackupFile.file_type.ilike('%document%')).count()
    other_count = max(0, total_backup_files - (photo_count + video_count + doc_count))

    # Recent activity
    recent_history = db_session.query(BackupHistory).order_by(BackupHistory.created_at.desc()).limit(10).all()
    recent_acts = []
    for h in recent_history:
        u_name = h.user.name if h.user else "User"
        recent_acts.append({
            'id': h.id,
            'action': h.action or 'Backup',
            'status': h.status or 'Completed',
            'userName': u_name,
            'device': h.source_device or 'Unknown Device',
            'timestamp': h.created_at.isoformat() if h.created_at else None
        })

    # Recent transactions
    recent_txs = db_session.query(Transaction).order_by(Transaction.created_at.desc()).limit(6).all()
    recent_tx_list = [tx.to_dict() for tx in recent_txs]

    return jsonify({
        'status': 'ok',
        'metrics': metrics,
        'stats': {
            'totalUsers': total_users,
            'activeUsers': active_users,
            'suspendedUsers': suspended_users,
            'totalConnectedAccounts': total_connected_accounts,
            'totalDevices': total_devices,
            'totalBackupFiles': total_backup_files,
            'totalStorageBytes': total_storage_bytes,
            'totalStorageFormatted': storage_formatted,
            'totalRevenue': total_revenue,
            'totalSubscriptions': total_subscriptions,
            'activeSubscriptions': active_subscriptions,
            'fileBreakdown': {
                'photos': photo_count,
                'videos': video_count,
                'documents': doc_count,
                'other': other_count
            }
        },
        'recentActivity': recent_acts,
        'recentTransactions': recent_tx_list
    }), 200

@app.route('/api/admin/users', methods=['GET'])
def admin_users():
    users = db_session.query(User).order_by(User.created_at.desc()).all()
    user_list = []
    for u in users:
        acc_list = [a.provider_email or a.email for a in u.connected_accounts if (a.provider_email or a.email)]
        dev_list = [d.device_name for d in u.devices if d.device_name]
        file_count = len(u.backup_files)
        storage_bytes = sum(f.file_size or 0 for f in u.backup_files)
        active_sub = db_session.query(Subscription).filter_by(user_id=u.id, status='active').first()
        
        user_list.append({
            'id': u.id,
            'name': u.name or u.display_name or 'Unknown',
            'email': u.email,
            'accountStatus': u.account_status or 'active',
            'createdAt': u.created_at.isoformat() if u.created_at else None,
            'connectedAccountsCount': len(acc_list),
            'connectedAccounts': acc_list,
            'devicesCount': len(dev_list),
            'devices': dev_list,
            'backupFilesCount': file_count,
            'totalStorageBytes': storage_bytes,
            'subscriptionPlan': active_sub.plan_name if active_sub else 'Free Plan',
            'subscriptionStatus': active_sub.status if active_sub else 'free'
        })
    return jsonify({'status': 'ok', 'users': user_list}), 200

@app.route('/api/admin/users/<user_id>/toggle-status', methods=['POST'])
def admin_toggle_user_status(user_id):
    user = db_session.query(User).filter_by(id=user_id).first()
    if not user:
        return jsonify({'error': 'User not found'}), 404
    
    user.account_status = 'suspended' if user.account_status == 'active' else 'active'
    db_session.commit()
    return jsonify({
        'status': 'ok',
        'userId': user.id,
        'newStatus': user.account_status,
        'message': f"User status changed to {user.account_status}"
    }), 200

@app.route('/api/admin/subscriptions', methods=['GET'])
def admin_subscriptions():
    subs = db_session.query(Subscription).order_by(Subscription.created_at.desc()).all()
    return jsonify({
        'status': 'ok',
        'subscriptions': [s.to_dict() for s in subs]
    }), 200

@app.route('/api/admin/transactions', methods=['GET'])
def admin_transactions():
    txs = db_session.query(Transaction).order_by(Transaction.created_at.desc()).all()
    return jsonify({
        'status': 'ok',
        'transactions': [t.to_dict() for t in txs]
    }), 200

@app.route('/api/admin/subscriptions/grant', methods=['POST'])
def admin_grant_subscription():
    data = request.get_json(silent=True) or {}
    user_id = data.get('userId')
    plan_name = data.get('planName', 'Pro Yearly')
    billing_cycle = data.get('billingCycle', 'yearly')
    amount = data.get('amount', 1999)

    user = db_session.query(User).filter_by(id=user_id).first()
    if not user:
        return jsonify({'error': 'User not found'}), 404

    existing = db_session.query(Subscription).filter_by(user_id=user.id, status='active').all()
    for e in existing:
        e.status = 'expired'

    duration_days = 365 if billing_cycle == 'yearly' else 30
    sub = Subscription(
        id=str(uuid.uuid4()),
        user_id=user.id,
        plan_name=plan_name,
        status='active',
        billing_cycle=billing_cycle,
        amount_paid=amount,
        starts_at=datetime.utcnow(),
        expires_at=datetime.utcnow() + timedelta(days=duration_days),
        created_at=datetime.utcnow()
    )
    db_session.add(sub)

    tx = Transaction(
        id=str(uuid.uuid4()),
        user_id=user.id,
        subscription_id=sub.id,
        razorpay_payment_id=f"admin_grant_{uuid.uuid4().hex[:12]}",
        amount=amount,
        currency='INR',
        status='success',
        payment_method='Admin Override / Manual',
        description=f"Admin Granted {plan_name}",
        created_at=datetime.utcnow()
    )
    db_session.add(tx)
    db_session.commit()

    return jsonify({
        'status': 'ok',
        'message': f"Subscription {plan_name} granted to {user.email}",
        'subscription': sub.to_dict()
    }), 200

@app.route('/api/subscriptions/current', methods=['GET'])
def get_current_subscription():
    user = None
    auth_header = request.headers.get('Authorization', '')
    if auth_header.startswith('Bearer '):
        token = auth_header.split(' ')[1]
        try:
            payload = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])
            user = db_session.query(User).filter_by(id=payload.get('user_id') or payload.get('id')).first()
        except Exception:
            pass
    if not user:
        uid = request.args.get('userId')
        if uid:
            user = db_session.query(User).filter_by(id=uid).first()

    if not user:
        return jsonify({'error': 'Unauthorized', 'isPro': False}), 401

    sub = user.active_subscription
    return jsonify({
        'status': 'ok',
        'isPro': user.is_pro,
        'planType': user.to_dict().get('planType', 'free'),
        'planName': user.to_dict().get('planName', 'Starter Free'),
        'subscription': sub.to_dict() if sub else None,
        'user': user.to_dict()
    }), 200

@app.route('/api/payments/razorpay/record', methods=['POST'])
@app.route('/api/payments/verify-id', methods=['POST'])
def record_razorpay_payment():
    data = request.get_json(silent=True) or {}
    user_id = data.get('userId')
    payment_id = data.get('razorpayPaymentId') or data.get('paymentId') or data.get('payment_id')
    order_id = data.get('razorpayOrderId') or data.get('orderId')
    amount = float(data.get('amount') or 1.0)
    plan_name = data.get('planName') or 'E Space Pro (Annual)'
    billing_cycle = data.get('billingCycle') or 'yearly'
    payment_method = data.get('paymentMethod') or 'UPI / Razorpay'

    user = None
    if user_id:
        user = db_session.query(User).filter_by(id=user_id).first()
    if not user:
        auth_header = request.headers.get('Authorization', '')
        if auth_header.startswith('Bearer '):
            token = auth_header.split(' ')[1]
            try:
                payload = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])
                user = db_session.query(User).filter_by(id=payload.get('user_id') or payload.get('id')).first()
            except Exception:
                pass

    if not user:
        return jsonify({'error': 'User authentication required'}), 401

    if not payment_id:
        return jsonify({'error': 'Payment ID (e.g. pay_...) is required'}), 400

    payment_id = payment_id.strip()

    # Expire previous subscriptions
    existing_subs = db_session.query(Subscription).filter_by(user_id=user.id, status='active').all()
    for es in existing_subs:
        es.status = 'replaced'

    duration_days = 365 if billing_cycle == 'yearly' else 30
    sub = Subscription(
        id=str(uuid.uuid4()),
        user_id=user.id,
        plan_type='pro',
        plan_name=plan_name if 'Pro' in plan_name else f"E Space Pro ({plan_name})",
        status='active',
        billing_cycle=billing_cycle,
        amount_paid=amount,
        price_inr=int(amount),
        currency='INR',
        max_accounts=999,
        valid_days=duration_days,
        starts_at=datetime.utcnow(),
        expires_at=datetime.utcnow() + timedelta(days=duration_days),
        auto_renew=False,
        payment_method=payment_method,
        transaction_id=payment_id,
        created_at=datetime.utcnow()
    )
    db_session.add(sub)
    db_session.flush()

    # Check if transaction exists
    existing_tx = db_session.query(Transaction).filter_by(razorpay_payment_id=payment_id).first()
    if not existing_tx:
        existing_tx = Transaction(
            id=str(uuid.uuid4()),
            user_id=user.id,
            subscription_id=sub.id,
            razorpay_payment_id=payment_id,
            razorpay_order_id=order_id,
            amount=int(amount),
            currency='INR',
            status='success',
            payment_method=payment_method,
            description=f"Online Payment for {sub.plan_name}",
            payment_gateway='razorpay',
            gateway_ref=payment_id,
            created_at=datetime.utcnow()
        )
        db_session.add(existing_tx)
    else:
        existing_tx.subscription_id = sub.id
        existing_tx.user_id = user.id
        existing_tx.status = 'success'

    db_session.commit()

    return jsonify({
        'status': 'ok',
        'isPro': True,
        'message': 'Payment verified and E Space Pro activated successfully!',
        'user': user.to_dict(),
        'subscription': sub.to_dict(),
        'transaction': existing_tx.to_dict()
    }), 200

# ==========================================
# REFERRAL & REWARDS API ROUTES
# ==========================================
@app.route('/api/referrals/my-code', methods=['GET'])
@auth_required
def get_my_referral_code():
    user = request.current_user
    if not user:
        return jsonify({'error': 'Unauthorized'}), 401

    # Ensure user has a permanent memorable referral code
    if not user.referral_code or user.referral_code.startswith('ESPACEBAD'):
        new_code = generate_referral_code(user.name, user.email, user.id)
        # Verify uniqueness
        existing = db_session.query(User).filter(User.referral_code == new_code, User.id != user.id).first()
        if not existing:
            user.referral_code = new_code
            db_session.commit()

    ref_code = user.referral_code
    base_url = request.host_url.rstrip('/')
    referral_link = f"{base_url}/register?ref={ref_code}"

    refs = db_session.query(Referral).filter_by(referrer_id=user.id).order_by(Referral.created_at.desc()).all()
    total_referrals = user.referral_count or len(refs)
    required_for_vip = 2
    is_vip = total_referrals >= required_for_vip or user.is_pro
    vip_days = user.active_subscription.days_remaining if user.active_subscription else (365 if is_vip else 0)

    return jsonify({
        'status': 'ok',
        'referralCode': ref_code,
        'referralLink': referral_link,
        'totalReferrals': total_referrals,
        'requiredForVip': required_for_vip,
        'isVipUnlocked': is_vip,
        'vipDaysRemaining': vip_days,
        'referrals': [r.to_dict() for r in refs]
    }), 200

@app.route('/api/referrals/apply', methods=['POST'])
@auth_required
def apply_referral_code():
    user = request.current_user
    if not user:
        return jsonify({'error': 'Unauthorized'}), 401

    data = request.get_json(silent=True) or {}
    code = (data.get('code') or '').strip().upper()
    if not code:
        return jsonify({'error': 'Please enter a referral code'}), 400

    if user.referred_by_id:
        return jsonify({'error': 'You have already applied a referral code'}), 400

    referrer = db_session.query(User).filter_by(referral_code=code).first()
    if not referrer:
        return jsonify({'error': f"Invalid referral code '{code}'. Please check and try again."}), 404

    if referrer.id == user.id:
        return jsonify({'error': 'You cannot use your own referral code'}), 400

    user.referred_by_id = referrer.id
    referrer.referral_count = (referrer.referral_count or 0) + 1

    ref_record = Referral(
        id=str(uuid.uuid4()),
        referrer_id=referrer.id,
        referred_user_id=user.id,
        referred_email=user.email,
        referral_code=code,
        status='completed',
        reward_granted=True,
        reward_description='Referral bonus unlocked',
        created_at=datetime.utcnow(),
        completed_at=datetime.utcnow()
    )
    db_session.add(ref_record)

    # Check if referrer unlocked VIP pass (>= 2 referrals)
    if referrer.referral_count >= 2:
        existing_sub = db_session.query(Subscription).filter_by(user_id=referrer.id, status='active').first()
        if not existing_sub:
            vip_sub = Subscription(
                id=str(uuid.uuid4()),
                user_id=referrer.id,
                plan_type='referral_vip',
                plan_name='Referral VIP Pass (1 Year Free)',
                status='active',
                billing_cycle='yearly',
                amount_paid=0.0,
                price_inr=0,
                currency='INR',
                max_accounts=999,
                valid_days=365,
                starts_at=datetime.utcnow(),
                expires_at=datetime.utcnow() + timedelta(days=365),
                auto_renew=False,
                payment_method='referral_reward',
                transaction_id=f"REF-VIP-{ref_record.id[:8]}",
                created_at=datetime.utcnow()
            )
            db_session.add(vip_sub)

    db_session.commit()

    return jsonify({
        'status': 'ok',
        'message': f"Referral code {code} applied successfully! 1-Year Free Storage Pass unlocked."
    }), 200

# ==========================================
# DIRECT APK DOWNLOAD ROUTE
# ==========================================
@app.route('/download/app', methods=['GET'])
@app.route('/download/apk', methods=['GET'])
def download_app_apk():
    apk_file = config.get_release_apk_path()
    if apk_file and os.path.exists(apk_file):
        return send_file(apk_file, as_attachment=True, download_name='ESpace.apk', mimetype='application/vnd.android.package-archive')
    candidates = [
        os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'release', 'ESpace.apk'),
        os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'release', 'ESpace.apk'),
        os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'release', 'ESpace.apk'),
        os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'web', 'dist', 'ESpace.apk'),
    ]
    for p in candidates:
        if os.path.exists(p):
            return send_file(p, as_attachment=True, download_name='ESpace.apk', mimetype='application/vnd.android.package-archive')
    return jsonify({'error': 'ESpace.apk file not found on server'}), 404

# ==========================================
# SERVE WEB APPLICATION FRONTEND (React SPA)
# ==========================================
WEB_DIST = config.get_web_dist()

@app.after_request
def add_cache_headers(response):
    if request.path == '/' or request.path.endswith('.html') or not '.' in request.path:
        response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate, max-age=0'
        response.headers['Pragma'] = 'no-cache'
        response.headers['Expires'] = '0'
    return response

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve_spa(path):
    if path.startswith('api/') or path == 'health':
        return jsonify({'error': 'API endpoint not found'}), 404

    target = os.path.join(WEB_DIST, path)
    if os.path.exists(target) and not os.path.isdir(target):
        return send_file(target)

    index_file = os.path.join(WEB_DIST, 'index.html')
    if os.path.exists(index_file):
        return send_file(index_file)

    return jsonify({
        'service': 'CloudVault 2.0 API',
        'status': 'online',
        'webApp': 'Built dist assets available'
    }), 200

if __name__ == '__main__':
    init_db()
    print(f"E Space 2.0 Backend running on http://{config.HOST}:{config.PORT}...")
    app.run(host=config.HOST, port=config.PORT, debug=False)
