import json
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Tuple


@dataclass
class Config:
    server: str
    token: str
    captcha2_key: Optional[str] = None
    monitor_index: int = 1
    window_size: Tuple[int, int] = (1280, 900)
    headless: bool = False
    diag_dir: str = "./diag"
    log_file: str = "./formfill-sb.log"
    signup_save_as_site: str = "spotify-new"
    heartbeat_url_poll_seconds: int = 2
    signup_timeout_seconds: int = 900
    proxy: Optional[str] = None  # "user:pass@host:port" — SB proxy arg
    config_path: Path = field(default_factory=lambda: Path("config.json"))

    @property
    def server_root(self) -> str:
        return self.server.rstrip("/")

    def url(self, path: str) -> str:
        return self.server_root + (path if path.startswith("/") else "/" + path)


def load(path: Optional[str] = None) -> Config:
    env_path = os.environ.get("FORMFILL_SB_CONFIG")
    cfg_path = Path(path or env_path or "config.json")
    if not cfg_path.exists():
        raise SystemExit(f"config not found at {cfg_path.resolve()}; copy config.example.json to config.json and fill it in")
    raw = json.loads(cfg_path.read_text(encoding="utf-8"))
    ws = raw.get("window_size") or [1280, 900]
    return Config(
        server=raw["server"],
        token=raw["token"],
        captcha2_key=raw.get("captcha2_key") or None,
        monitor_index=int(raw.get("monitor_index", 1)),
        window_size=(int(ws[0]), int(ws[1])),
        headless=bool(raw.get("headless", False)),
        diag_dir=raw.get("diag_dir", "./diag"),
        log_file=raw.get("log_file", "./formfill-sb.log"),
        signup_save_as_site=raw.get("signup_save_as_site", "spotify-new"),
        heartbeat_url_poll_seconds=int(raw.get("heartbeat_url_poll_seconds", 2)),
        signup_timeout_seconds=int(raw.get("signup_timeout_seconds", 900)),
        proxy=raw.get("proxy") or None,
        config_path=cfg_path.resolve(),
    )
