"""
============================================================================
🌐 CENTRALIZED BACKEND CONFIGURATION & ENVIRONMENT LOADER
============================================================================
All configuration values in this file are read dynamically from your .env file.
If you ever want to change ports, URLs, database credentials, API keys, or paths,
change them in the .env file!
============================================================================
"""

import os
import sys
from dotenv import load_dotenv

# Search for .env in current directory, parent directories, and backend directory
_current_dir = os.path.dirname(os.path.abspath(__file__))
_parent_dir = os.path.dirname(_current_dir)
_grandparent_dir = os.path.dirname(_parent_dir)

# Load master config.py variables into environment if present
for cfg_py in [
    os.path.join(_parent_dir, 'config.py'),
    os.path.join(_grandparent_dir, 'config.py'),
    os.path.join(os.getcwd(), 'config.py'),
]:
    if os.path.exists(cfg_py):
        try:
            import runpy
            _mod = runpy.run_path(cfg_py)
            for _k, _v in _mod.items():
                if _k.isupper() and not _k.startswith('_'):
                    os.environ[_k] = str(_v)
            break
        except Exception:
            pass

for env_path in [
    os.path.join(_current_dir, '.env'),
    os.path.join(_parent_dir, '.env'),
    os.path.join(_grandparent_dir, '.env'),
    os.path.join(os.getcwd(), '.env'),
]:
    if os.path.exists(env_path):
        load_dotenv(env_path, override=False)


class BackendConfig:
    # ==========================================================================
    # 1. SERVER, NETWORK & BASE URLS
    # ==========================================================================
    PORT = int(os.environ.get("PORT", 5000))
    HOST = os.environ.get("HOST", "0.0.0.0")

    # Primary Base URL of backend API
    BASE_URL = os.environ.get("BASE_URL", f"http://127.0.0.1:{PORT}").rstrip('/')

    # Frontend Web Portal Base URL
    FRONTEND_URL = os.environ.get("FRONTEND_URL", BASE_URL).rstrip('/')

    # Production Cloud Server Base URL (When deployed to VPS/Cloud, e.g. https://api.yourdomain.com)
    PRODUCTION_URL = os.environ.get("PRODUCTION_URL", "").rstrip('/')

    # Public Cloudflare Edge tunnel or reverse proxy URL
    PUBLIC_EDGE_URL = os.environ.get(
        "PUBLIC_EDGE_URL",
        "https://reno-bay-tagged-scout.trycloudflare.com"
    ).rstrip('/')

    # Local Wi-Fi Network IPv4
    WIFI_BASE_URL = os.environ.get(
        "WIFI_BASE_URL",
        f"http://10.198.118.101:{PORT}"
    ).rstrip('/')

    # ==========================================================================
    # 2. DATABASE CONFIGURATION (XAMPP MySQL / SQLite)
    # ==========================================================================
    DB_ENGINE = os.environ.get("DB_ENGINE", "mysql").lower()
    MYSQL_HOST = os.environ.get("MYSQL_HOST", "127.0.0.1")
    MYSQL_PORT = int(os.environ.get("MYSQL_PORT", 3307))
    MYSQL_USER = os.environ.get("MYSQL_USER", "root")
    MYSQL_PASSWORD = os.environ.get("MYSQL_PASSWORD", "")
    MYSQL_DB = os.environ.get("MYSQL_DB", "cloudvault")

    DATABASE_URL = os.environ.get(
        "DATABASE_URL",
        f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB}?charset=utf8mb4"
    )

    SQLITE_DB_PATH = os.environ.get(
        "SQLITE_DB_PATH",
        os.path.join(_current_dir, "cloudvault_central.db")
    )

    # ==========================================================================
    # 3. GOOGLE DRIVE & OAUTH 2.0 CREDENTIALS
    # ==========================================================================
    GOOGLE_CLIENT_ID = os.environ.get(
        "GOOGLE_CLIENT_ID",
        "1033028674120-cckgpja5lpchtiv2uk6s30fi892i88p3.apps.googleusercontent.com"
    )
    GOOGLE_CLIENT_SECRET = os.environ.get(
        "GOOGLE_CLIENT_SECRET",
        "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"
    )

    GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
    GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"
    GOOGLE_USERINFO_URL = "https://www.googleapis.com/oauth2/v2/userinfo"
    GOOGLE_DRIVE_API_BASE = "https://www.googleapis.com/drive/v3"
    GOOGLE_DRIVE_UPLOAD_BASE = "https://www.googleapis.com/upload/drive/v3"

    GOOGLE_OAUTH_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"
    ]

    @classmethod
    def get_oauth_redirect_uri(cls, custom_base_url=None):
        configured = os.environ.get("GOOGLE_REDIRECT_URI")
        if configured:
            return configured
        base = (custom_base_url or cls.BASE_URL).rstrip('/')
        return f"{base}/api/drive/callback"

    # ==========================================================================
    # 4. PAYMENT GATEWAY & MONETIZATION (Razorpay / UPI)
    # ==========================================================================
    RAZORPAY_KEY_ID = os.environ.get("RAZORPAY_KEY_ID", "pl_RBcBgFQx5N2HsF")
    RAZORPAY_KEY_SECRET = os.environ.get("RAZORPAY_KEY_SECRET", "")
    RAZORPAY_PAYMENT_URL = os.environ.get("RAZORPAY_PAYMENT_URL", "https://razorpay.me/@indsac")

    PRO_PRICE_INR = float(os.environ.get("PRO_PRICE_INR", 1.0))
    REFERRAL_VIP_REQUIRED_COUNT = int(os.environ.get("REFERRAL_VIP_REQUIRED_COUNT", 2))

    # ==========================================================================
    # 5. SECURITY & JWT AUTHENTICATION
    # ==========================================================================
    JWT_SECRET = os.environ.get("JWT_SECRET_KEY", os.environ.get("JWT_SECRET", "cloudvault_super_secret_jwt_key_2026"))
    JWT_ALGORITHM = os.environ.get("JWT_ALGORITHM", "HS256")
    JWT_EXPIRATION_HOURS = int(os.environ.get("JWT_EXPIRATION_HOURS", 24))

    # ==========================================================================
    # 6. FILE PATHS & DIRECTORIES
    # ==========================================================================
    @classmethod
    def get_upload_folder(cls):
        custom = os.environ.get("UPLOAD_FOLDER")
        if custom and os.path.isabs(custom):
            path = custom
        elif custom:
            path = os.path.join(_parent_dir, custom)
        else:
            path = os.path.join(_current_dir, 'uploads')
        os.makedirs(path, exist_ok=True)
        return path

    @classmethod
    def get_web_dist(cls):
        custom = os.environ.get("WEB_DIST_PATH")
        candidates = [
            custom if custom and os.path.isabs(custom) else None,
            os.path.join(_parent_dir, custom) if custom else None,
            os.path.join(_parent_dir, 'web', 'dist'),
            os.path.join(_current_dir, '..', 'web', 'dist'),
            os.path.join(_grandparent_dir, 'web', 'dist'),
        ]
        for c in candidates:
            if c and os.path.exists(c):
                return os.path.abspath(c)
        return os.path.abspath(os.path.join(_parent_dir, 'web', 'dist'))

    @classmethod
    def get_release_apk_path(cls):
        custom = os.environ.get("RELEASE_APK_PATH")
        candidates = [
            custom if custom and os.path.isabs(custom) else None,
            os.path.join(_parent_dir, custom) if custom else None,
            os.path.join(cls.get_web_dist(), 'ESpace.apk'),
            os.path.join(_parent_dir, 'release', 'ESpace.apk'),
            os.path.join(_grandparent_dir, 'release', 'ESpace.apk'),
        ]
        for c in candidates:
            if c and os.path.exists(c):
                return os.path.abspath(c)
        return None


config = BackendConfig()

# Run automatic config synchronization on import
try:
    from backend.sync_config import sync_all_configs
    sync_all_configs()
except Exception:
    pass

