import sys
from dataclasses import dataclass
from pathlib import Path

INPUT = Path(__file__).resolve().parent.parent / "input"


def _err(msg):
    print(f"[!] {msg}")
    sys.exit(1)


def _read_lines(path):
    with path.open(encoding="utf-8") as f:
        return [line.strip() for line in f if line.strip()]


@dataclass
class Config:
    worker: int
    timeout: int
    retry: int
    solver: str
    cap_key: str


def load_config():
    path = INPUT / "config.txt"
    if not path.exists():
        _err("input/config.txt not found")

    raw = {}
    for line in _read_lines(path):
        if "=" not in line:
            continue
        key, _, value = line.partition("=")
        raw[key.strip()] = value.strip()

    for p in ("worker", "timeout", "retry", "solver", "captcha_key"):
        if p not in raw:
            _err(f'config: missing "{p}"')

    solver = raw["solver"].lower()
    if solver not in ("capmonster", "capsolver"):
        _err(f'config: solver must be "capmonster" or "capsolver", got "{solver}"')

    return Config(
        worker=max(1, int(raw["worker"])),
        timeout=int(raw["timeout"]),
        retry=int(raw["retry"]),
        solver=solver,
        cap_key=raw["captcha_key"],
    )


@dataclass
class Proxy:
    host: str
    port: str
    username: str
    password: str

    @property
    def url(self):
        return f"http://{self.username}:{self.password}@{self.host}:{self.port}"

    @property
    def raw(self):
        return f"{self.host}:{self.port}:{self.username}:{self.password}"


def load_proxies():
    path = INPUT / "proxies.txt"
    if not path.exists():
        _err("input/proxies.txt not found")
    lines = _read_lines(path)
    if not lines:
        _err("input/proxies.txt is empty")

    result = []
    for line in lines:
        parts = line.split(":")
        if len(parts) < 4:
            _err(f'proxy: invalid format "{line}" (host:port:user:pass)')
        host, port = parts[0], parts[1]
        login = ":".join(parts[2:-1])
        pwd = parts[-1]
        result.append(Proxy(host, port, login, pwd))
    return result


def load_combos():
    path = INPUT / "combos.txt"
    if not path.exists():
        _err("input/combos.txt not found")

    result = []
    for line in _read_lines(path):
        parts = line.split(":", 1)
        if len(parts) == 2:
            result.append((parts[0].strip(), parts[1].strip()))

    if not result:
        _err("input/combos.txt: no valid combos (email:password)")
    return result
