"""
config.py — reads and writes config.json.

On first run, automatically migrates credentials from .env if present.
"""

import json
import os
from pathlib import Path

APP_DIR     = Path(__file__).parent
CONFIG_PATH = APP_DIR / "config.json"

DEFAULT = {
    "accounts":              [],    # [{"email": "...", "app_password": "..."}]
    "sound_enabled":         True,
    "launch_at_login":       False,
    "idle_refresh_minutes":  20,    # how often to recycle the IMAP IDLE connection
}


def load():
    cfg = dict(DEFAULT)
    if CONFIG_PATH.exists():
        try:
            cfg.update(json.loads(CONFIG_PATH.read_text()))
        except Exception:
            pass

    # One-time migration from .env → config.json
    if not cfg["accounts"]:
        _migrate_from_env(cfg)

    return cfg


def save(cfg):
    CONFIG_PATH.write_text(json.dumps(cfg, indent=2))


def mtime():
    """Return config.json modification time (0 if missing)."""
    try:
        return CONFIG_PATH.stat().st_mtime
    except FileNotFoundError:
        return 0


# ── Migration ─────────────────────────────────────────────────────────────────

def _migrate_from_env(cfg):
    """Read OTP_EMAIL / OTP_APP_PASSWORD from .env and add to accounts list."""
    env_path = APP_DIR / ".env"
    if not env_path.exists():
        return

    env = {}
    for line in env_path.read_text().splitlines():
        line = line.strip()
        if line and not line.startswith("#") and "=" in line:
            k, v = line.split("=", 1)
            env[k.strip()] = v.strip().strip('"').strip("'")

    email    = env.get("OTP_EMAIL", "")
    password = env.get("OTP_APP_PASSWORD", "")
    if email and password:
        cfg["accounts"].append({"email": email, "app_password": password})
        print("[config] Migrated credentials from .env → config.json")
