"""
============================================================================
🌐 E SPACE 2.0 - MASTER CONFIGURATION SYNCHRONIZER
============================================================================
This script reads the master config.py (or .env) in your project root and
automatically synchronizes:
1. Flutter Mobile App config (lib/config/app_config.dart)
2. React Web App config (web/.env)
3. Inner & outer config.py and .env files

You only need to edit ONE file: c:\\Users\\asus\\Desktop\\espaceapp\\config.py
Everything else is synchronized automatically!
============================================================================
"""

import os
import re
import sys
import runpy

def get_workspace_root():
    """Finds root workspace containing config.py or .env"""
    current = os.path.dirname(os.path.abspath(__file__))
    parent = os.path.dirname(current)
    grandparent = os.path.dirname(parent)

    for candidate in [os.getcwd(), parent, grandparent, current]:
        if (os.path.exists(os.path.join(candidate, 'config.py')) or os.path.exists(os.path.join(candidate, '.env'))) and os.path.exists(os.path.join(candidate, 'backend')):
            return os.path.abspath(candidate)
    return os.path.abspath(parent)

def load_master_config(workspace_root):
    """Loads configuration dictionary from config.py (preferred) or .env (fallback)"""
    config_dict = {}

    # 1. Try master config.py in root workspace
    config_py = os.path.join(workspace_root, 'config.py')
    if not os.path.exists(config_py):
        config_py = os.path.join(workspace_root, 'espaceapp', 'config.py')

    if os.path.exists(config_py):
        try:
            mod = runpy.run_path(config_py)
            for k, v in mod.items():
                if k.isupper() and not k.startswith('_'):
                    config_dict[k] = str(v) if not isinstance(v, (str, int, float, bool)) else v
            config_dict['_source'] = 'config.py'
            return config_dict
        except Exception as e:
            print(f"[WARN] Error running {config_py}: {e}")

    # 2. Fallback to .env file
    env_file = os.path.join(workspace_root, '.env')
    if not os.path.exists(env_file):
        env_file = os.path.join(workspace_root, 'espaceapp', '.env')

    if os.path.exists(env_file):
        with open(env_file, 'r', encoding='utf-8', errors='ignore') as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith('#'):
                    continue
                if '=' in line:
                    key, val = line.split('=', 1)
                    config_dict[key.strip()] = val.strip().strip("'\"")
        config_dict['_source'] = '.env'

    return config_dict

def sync_app_config_dart(cfg, workspace_root):
    """Generates and writes synchronized lib/config/app_config.dart"""
    production_url = str(cfg.get('PRODUCTION_URL', '')).strip().rstrip('/')
    public_edge_url = str(cfg.get('PUBLIC_EDGE_URL', 'https://figured-chorus-vendors-assistant.trycloudflare.com')).strip().rstrip('/')
    wifi_base_url = str(cfg.get('WIFI_BASE_URL', 'http://10.198.118.101:5000')).strip().rstrip('/')
    base_url = str(cfg.get('BASE_URL', 'http://127.0.0.1:5000')).strip().rstrip('/')
    port = str(cfg.get('PORT', '5000')).strip()

    candidate_entries = []
    if production_url:
        candidate_entries.append("    productionBaseUrl,")
    candidate_entries.append("    publicEdgeBaseUrl,")
    candidate_entries.append("    currentWifiBaseUrl,")
    candidate_entries.append("    legacyWifiBaseUrl,")
    candidate_entries.append("    olderWifiBaseUrl,")
    candidate_entries.append("    defaultEmulatorBaseUrl,")
    candidate_entries.append("    defaultLocalhostBaseUrl,")

    candidates_code = "\n".join(candidate_entries)

    content = f"""/// ============================================================================
/// 🌐 CENTRALIZED APP CONFIGURATION & BASE URLS
/// ============================================================================
/// NOTE: This file is AUTOMATICALLY SYNCHRONIZED from master config.py!
/// Do NOT manually edit this file. Edit config.py in the root directory and run:
///   sync_config.bat  (or start_backend.bat)
/// ============================================================================
library;

class AppConfig {{
  AppConfig._();

  // ==========================================================================
  // 1. BASE URLS (Synchronized from master config.py)
  // ==========================================================================

  /// Production Cloud Server URL (24/7 global server, empty if not yet deployed)
  static const String productionBaseUrl = '{production_url}';

  /// Public Cloudflare Edge tunnel (Accessible globally on 4G, 5G, and any Wi-Fi)
  static const String publicEdgeBaseUrl = '{public_edge_url}';

  /// Local Wi-Fi Network Backend IP & Port
  /// (Update this in config.py if your laptop's Wi-Fi IPv4 address changes)
  static const String currentWifiBaseUrl = '{wifi_base_url}';

  /// Alias for the primary host Wi-Fi base URL
  static const String hostWifiBaseUrl = currentWifiBaseUrl;

  /// Default Android Emulator Loopback URL
  static const String defaultEmulatorBaseUrl = 'http://10.0.2.2:{port}';

  /// Default Localhost Loopback URL (Web / Desktop / ADB Reverse)
  static const String defaultLocalhostBaseUrl = '{base_url}';

  /// Legacy/Alternate Wi-Fi Fallbacks
  static const String legacyWifiBaseUrl = 'http://192.168.1.15:5000';
  static const String olderWifiBaseUrl = 'http://10.73.84.101:5000';

  /// Network Probe & Failover Candidates
  /// The app will automatically test these in order to find an active server
  static const List<String> candidateUrls = [
{candidates_code}
  ];

  /// Default network request timeout
  static const Duration requestTimeout = Duration(seconds: 15);

  // ==========================================================================
  // 2. API ENDPOINTS (Relative paths)
  // ==========================================================================

  // --- Health & Public Config ---
  static const String health = '/health';
  static const String publicConfig = '/api/config/public';

  // --- Authentication ---
  static const String authRegister = '/api/auth/register';
  static const String authLogin = '/api/auth/login';
  static const String authRefresh = '/api/auth/refresh';
  static const String authLogout = '/api/auth/logout';
  static const String authMe = '/api/auth/me';
  static const String authChangePassword = '/api/auth/change-password';
  static const String authForgotPassword = '/api/auth/forgot-password';

  // --- Google Drive & Multi-Cloud Accounts ---
  static const String driveOAuthConfig = '/api/drive/oauth-config';
  static const String driveAuthUrl = '/api/drive/auth-url';
  static const String driveCallback = '/api/drive/callback';
  static const String cloudProviders = '/api/cloud-providers';
  static const String driveAccounts = '/api/drive/accounts';
  static const String cloudAccounts = '/api/cloud/accounts';

  // --- Storage Quota & Targets ---
  static const String storageQuota = '/api/storage/quota';
  static const String storageTargets = '/api/storage/targets';

  // --- Files & Uploads ---
  static const String driveFiles = '/api/drive/files';
  static const String driveUploadInit = '/api/drive/upload-init';
  static const String driveUploadComplete = '/api/drive/upload-complete';
  static const String driveUploadFile = '/api/drive/upload-file';
  static const String driveDownload = '/api/drive/download';
  static const String drivePreview = '/api/drive/preview';
  static const String driveBulkDelete = '/api/drive/files/bulk-delete';
  static const String driveSync = '/api/drive/sync';

  // --- Devices & Backup Queue ---
  static const String devices = '/api/devices';
  static const String backupQueue = '/api/backup/queue';
  static const String backupHistory = '/api/backup/history';
  static const String settings = '/api/settings';
  static const String userSync = '/api/user/sync';
  static const String backupSync = '/api/backup/sync';

  // --- Referral & Monetization Program ---
  static const String referralMyCode = '/api/referrals/my-code';
  static const String referralApply = '/api/referrals/apply';
  static const String viralStorageCard = '/api/storage/viral-card';
  static const String subscriptionsCurrent = '/api/subscriptions/current';
  static const String subscriptionsActivateInr1 = '/api/subscriptions/activate-inr1';
  static const String subscriptionsRenew = '/api/subscriptions/renew';

  // ==========================================================================
  // 3. URL BUILDER HELPER
  // ==========================================================================
  /// Combines a base URL with an endpoint path cleanly (avoiding double slashes)
  static String buildUrl(String baseUrl, String endpoint) {{
    final cleanBase = baseUrl.trim().replaceAll(RegExp(r'/+$'), '');
    final cleanEndpoint = endpoint.trim().startsWith('/') ? endpoint.trim() : '/$endpoint';
    return '$cleanBase$cleanEndpoint';
  }}
}}
"""
    targets = [
        os.path.join(workspace_root, 'lib', 'config', 'app_config.dart'),
        os.path.join(workspace_root, 'espaceapp', 'lib', 'config', 'app_config.dart'),
    ]
    for target in targets:
        os.makedirs(os.path.dirname(target), exist_ok=True)
        with open(target, 'w', encoding='utf-8') as f:
            f.write(content)

def sync_web_env(cfg, workspace_root):
    """Generates web/.env matching the master configuration"""
    web_content = f"""# ==============================================================================
# 🌐 E SPACE 2.0 - REACT FRONTEND CONFIGURATION (.env)
# Automatically synced from master config.py
# ==============================================================================
VITE_API_URL=
VITE_APP_TITLE=E Space - Cloud Storage Manager
VITE_APP_VERSION=2.0.0
"""
    targets = [
        os.path.join(workspace_root, 'web', '.env'),
        os.path.join(workspace_root, 'espaceapp', 'web', '.env'),
    ]
    for target in targets:
        os.makedirs(os.path.dirname(target), exist_ok=True)
        with open(target, 'w', encoding='utf-8') as f:
            f.write(web_content)

def sync_env_file(cfg, workspace_root):
    """Generates .env from config.py for backwards compatibility with any dotenv tools"""
    env_lines = [
        "# ==============================================================================",
        "# 🌐 E SPACE 2.0 - ENVIRONMENT VARIABLES (.env)",
        "# Automatically generated from master config.py",
        "# ==============================================================================",
    ]
    for k, v in cfg.items():
        if not k.startswith('_'):
            env_lines.append(f"{k}={v}")

    env_content = "\n".join(env_lines) + "\n"

    targets = [
        os.path.join(workspace_root, '.env'),
        os.path.join(workspace_root, 'espaceapp', '.env'),
    ]
    for target in targets:
        try:
            with open(target, 'w', encoding='utf-8') as f:
                f.write(env_content)
        except Exception:
            pass

def sync_all_configs():
    """Main function to synchronize all configurations across the project"""
    root = get_workspace_root()
    cfg = load_master_config(root)

    if not cfg:
        print(f"[ERROR] Could not find config.py or .env in {root}!")
        return False

    source_file = cfg.get('_source', 'config.py')

    # 1. Sync Flutter app_config.dart
    sync_app_config_dart(cfg, root)

    # 2. Sync React Web .env
    sync_web_env(cfg, root)

    # 3. Sync .env for system compatibility
    sync_env_file(cfg, root)

    # 4. Sync inner config.py if outer config.py exists
    outer_cfg_py = os.path.join(root, 'config.py')
    inner_cfg_py = os.path.join(root, 'espaceapp', 'config.py')
    if os.path.exists(outer_cfg_py) and os.path.exists(os.path.dirname(inner_cfg_py)):
        try:
            with open(outer_cfg_py, 'r', encoding='utf-8') as src:
                txt = src.read()
            with open(inner_cfg_py, 'w', encoding='utf-8') as dst:
                dst.write(txt)
        except Exception:
            pass

    print(f"[CONFIG SYNC] Successfully synchronized {source_file} across:")
    print(f"  -> Flutter Mobile: lib/config/app_config.dart")
    print(f"  -> React Frontend: web/.env")
    print(f"  -> System Config:  .env")
    print(f"  -> Active URLs:")
    if cfg.get('PRODUCTION_URL'):
        print(f"     * Production Server: {cfg.get('PRODUCTION_URL')}")
    print(f"     * Cloudflare Tunnel: {cfg.get('PUBLIC_EDGE_URL')}")
    print(f"     * Local Wi-Fi IPv4:  {cfg.get('WIFI_BASE_URL')}")
    print(f"     * Localhost / Port:  {cfg.get('BASE_URL')} (Port: {cfg.get('PORT', 5000)})")
    return True

if __name__ == '__main__':
    sync_all_configs()
