from __future__ import annotations

from dataclasses import dataclass
from typing import Literal, Optional

from PyQt6.QtCore import QSettings
from platformdirs import user_data_dir


ModelSize = Literal["tiny", "base", "small", "medium", "large"]


@dataclass
class AppConfig:
    model_dir: str
    model_size: ModelSize = "medium"
    language: Optional[str] = None     # e.g. "en" or None for auto
    task: Literal["transcribe", "translate"] = "transcribe"


def default_model_dir() -> str:
    return user_data_dir("Whiscribe", "Whiscribe")


def load_config() -> AppConfig:
    s = QSettings()
    model_dir = s.value("model_dir", default_model_dir())
    model_size = s.value("model_size", "medium")
    language = s.value("language", "")
    task = s.value("task", "transcribe")

    language = language if isinstance(language, str) and language.strip() else None
    if model_size not in ("tiny", "base", "small", "medium", "large"):
        model_size = "medium"
    if task not in ("transcribe", "translate"):
        task = "transcribe"

    return AppConfig(
        model_dir=str(model_dir),
        model_size=model_size,   # type: ignore[assignment]
        language=language,
        task=task,               # type: ignore[assignment]
    )


def save_config(cfg: AppConfig) -> None:
    s = QSettings()
    s.setValue("model_dir", cfg.model_dir)
    s.setValue("model_size", cfg.model_size)
    s.setValue("language", cfg.language or "")
    s.setValue("task", cfg.task)
