import json
from dataclasses import dataclass
from pathlib import Path


@dataclass
class AppConfig:
    _conf: dict

    @classmethod
    def from_path(cls, path: str | None = None) -> "AppConfig":
        config_path = Path(path) if path else cls.default_config_path()

        if config_path.exists():
            conf = json.loads(config_path.read_text(encoding="utf-8"))
        else:
            conf = cls.default_config()

        return cls(conf)

    @staticmethod
    def default_config_path() -> Path:
        return Path(__file__).resolve().parent / "config.json"

    @staticmethod
    def default_config() -> dict:
        return {
            "success_output_folder": "JAV_output",
            "failed": {
                "move_enabled": False,
                "output_folder": "failed",
            },
            "proxy": {
                "proxy": "",
                "timeout": 10,
                "retry": 3,
            },
            "javbus": {
                "cookie": "existmag=all",
            },
            "scan": {
                "escape_folders": ["failed", "JAV_output"],
            },
            "subtitle_badge": {
                "enabled": True,
                "backup_enabled": True,
            },
            "image": {
                "jpeg_quality": 85,
                "optimize": True,
                "progressive": True,
            },
        }

    def proxy(self) -> tuple[str, int, int]:
        sec = self._conf.get("proxy", {})
        return (
            str(sec.get("proxy", "")),
            int(sec.get("timeout", 10)),
            int(sec.get("retry", 3)),
        )

    def success_folder(self) -> str:
        return str(self._conf.get("success_output_folder", "JAV_output"))

    def failed_move_enabled(self) -> bool:
        sec = self._conf.get("failed", {})
        return bool(sec.get("move_enabled", False))

    def failed_folder(self) -> str:
        sec = self._conf.get("failed", {})
        return str(sec.get("output_folder", "failed"))

    def escape_folders(self) -> list[str]:
        sec = self._conf.get("scan", {})
        folders = sec.get("escape_folders", ["failed", "JAV_output"])
        if isinstance(folders, list):
            return [str(x).strip() for x in folders if str(x).strip()]
        if isinstance(folders, str):
            return [x.strip() for x in folders.split(",") if x.strip()]
        return []

    def javbus_cookies(self) -> dict[str, str]:
        sec = self._conf.get("javbus", {})
        raw = str(sec.get("cookie", "existmag=all")).strip()
        if not raw:
            return {}

        cookies: dict[str, str] = {}
        for part in raw.split(";"):
            item = part.strip()
            if not item or "=" not in item:
                continue
            key, value = item.split("=", 1)
            key = key.strip()
            value = value.strip()
            if key:
                cookies[key] = value
        return cookies

    def subtitle_badge_enabled(self) -> bool:
        sec = self._conf.get("subtitle_badge", {})
        return bool(sec.get("enabled", True))

    def subtitle_badge_backup_enabled(self) -> bool:
        sec = self._conf.get("subtitle_badge", {})
        return bool(sec.get("backup_enabled", True))

    def image_save_options(self) -> dict:
        sec = self._conf.get("image", {})
        return {
            "jpeg_quality": int(sec.get("jpeg_quality", 85)),
            "optimize": bool(sec.get("optimize", True)),
            "progressive": bool(sec.get("progressive", True)),
        }
