import os
from pathlib import Path

# Base Paths
BASE_DIR = Path(__file__).resolve().parent
ENV_FILE = BASE_DIR / ".env"


def _load_env_file(env_path: Path):
    """Loads environment variables from .env if present into os.environ."""
    if not env_path.exists():
        return
    try:
        with open(env_path, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#") or "=" not in line:
                    continue
                k, v = line.split("=", 1)
                k = k.strip()
                v = v.strip().strip('"').strip("'")
                if k and k not in os.environ:
                    os.environ[k] = v
    except Exception:
        pass


def _load_or_generate_encryption_key(env_path: Path) -> str:
    """
    Checks for the unlock encryption key in environment or .env.
    If empty or missing, generates a fresh random key and writes it to .env.
    """
    # 1. First check if os.environ already has a non-empty ENCRYPTION_KEY
    env_val = os.getenv("ENCRYPTION_KEY", "").strip()
    if env_val:
        return env_val

    # 2. Check in .env file directly
    lines = []
    found_key = False
    existing_key = ""

    if env_path.exists():
        try:
            with open(env_path, "r", encoding="utf-8") as f:
                lines = f.readlines()
            for line in lines:
                s = line.strip()
                if s.startswith("ENCRYPTION_KEY="):
                    found_key = True
                    val = s.split("=", 1)[1].strip().strip('"').strip("'")
                    if val:
                        existing_key = val
                    break
        except Exception:
            pass

    if existing_key:
        os.environ["ENCRYPTION_KEY"] = existing_key
        return existing_key

    # 3. Not found or empty: generate a new Fernet unlock key
    from cryptography.fernet import Fernet
    new_key = Fernet.generate_key().decode("utf-8")

    # 4. Save to .env
    try:
        if env_path.exists():
            new_lines = []
            replaced = False
            for line in lines:
                if line.strip().startswith("ENCRYPTION_KEY="):
                    new_lines.append(f"ENCRYPTION_KEY={new_key}\n")
                    replaced = True
                else:
                    new_lines.append(line)
            if not replaced:
                if new_lines and not new_lines[-1].endswith("\n"):
                    new_lines.append("\n")
                new_lines.append(f"\n# Jelszavak és tokenek feloldó jelszava / titkosítási kulcsa (automatikusan generálva)\nENCRYPTION_KEY={new_key}\n")
            with open(env_path, "w", encoding="utf-8") as f:
                f.writelines(new_lines)
        else:
            template = f"""# Mozisarok & Videa/VK Uploader Konfiguráció

# Adatbázis (MySQL) beállítások
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=
DB_NAME=uploader
DB_POOL_SIZE=4

# Mozisarok API & Embed Converter
MOZISAROK_API_BASE=https://api.mozisarok.hu
EMBED_CONVERTER_URL=http://node6.lunes.host:3093/api/process

# Párhuzamosítás és szeletméretek
VIDEA_CONCURRENCY=2
VIDEA_CHUNK_SIZE_MB=16
VK_CHUNK_SIZE_MB=16

# Jelszavak és tokenek feloldó jelszava / titkosítási kulcsa (automatikusan generálva ha üres volt)
ENCRYPTION_KEY={new_key}
"""
            with open(env_path, "w", encoding="utf-8") as f:
                f.write(template)
    except Exception as e:
        print(f"Warning: could not write ENCRYPTION_KEY to {env_path}: {e}")

    os.environ["ENCRYPTION_KEY"] = new_key
    return new_key


# Load existing .env variables if present
_load_env_file(ENV_FILE)

# Unlock / encryption master key
ENCRYPTION_KEY = _load_or_generate_encryption_key(ENV_FILE)

# Database connection settings (strictly loaded from .env file)
DB_HOST = os.getenv("DB_HOST", "")
DB_PORT = int(os.getenv("DB_PORT", "3306"))
DB_USER = os.getenv("DB_USER", "")
DB_PASSWORD = os.getenv("DB_PASSWORD", "")
DB_NAME = os.getenv("DB_NAME", "")
DB_POOL_SIZE = int(os.getenv("DB_POOL_SIZE", "4"))

# Mozisarok API
MOZISAROK_API_BASE = os.getenv("MOZISAROK_API_BASE", "https://api.mozisarok.hu")

# Embed Link Converter
EMBED_CONVERTER_URL = os.getenv("EMBED_CONVERTER_URL", "http://node6.lunes.host:3093/api/process")

# Default Videa and VK concurrency (egyszerre hány videót töltsön fel)
DEFAULT_VIDEA_CONCURRENCY = int(os.getenv("VIDEA_CONCURRENCY", "2"))
DEFAULT_VK_CONCURRENCY = int(os.getenv("VK_CONCURRENCY", "2"))

# Maximum simultaneous Videa videos in conversion (biztonsági korlát: max 16 konvertálás alatt)
MAX_VIDEA_CONVERTING = int(os.getenv("MAX_VIDEA_CONVERTING", "16"))

# Streaming Chunk Sizes (MB) - alapértelmezetten 16 MB mindkét szolgáltatóhoz
DEFAULT_VIDEA_CHUNK_SIZE_MB = int(os.getenv("VIDEA_CHUNK_SIZE_MB", "16"))
DEFAULT_VK_CHUNK_SIZE_MB = int(os.getenv("VK_CHUNK_SIZE_MB", "16"))

# Default Web Server Port
DEFAULT_SERVER_PORT = int(os.getenv("SERVER_PORT", "8000"))

# Default maximum RAM buffer for disk reading during uploads (MB) - alapértelmezetten 128 MB
DEFAULT_MAX_DISK_BUFFER_MB = int(os.getenv("MAX_DISK_BUFFER_MB", "128"))

# HTTP Client settings
DEFAULT_TIMEOUT = 30
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
