from __future__ import annotations

from ..extensions import db
from ..models import AppSetting


QUICK_TASK_DEFAULTS = {
    "quick_task_label_fast": "Schnell",
    "quick_task_label_normal": "Normal",
    "quick_task_label_medium": "Dauert etwas",
    "quick_task_label_heavy": "Aufwendig",
    "quick_task_label_super_heavy": "Super aufwendig",
    "quick_task_points_fast": 4,
    "quick_task_points_normal": 8,
    "quick_task_points_medium": 12,
    "quick_task_points_heavy": 18,
    "quick_task_points_super_heavy": 28,
}

QUICK_TASK_EFFORTS = [
    ("fast", "quick_task_label_fast", "quick_task_points_fast"),
    ("normal", "quick_task_label_normal", "quick_task_points_normal"),
    ("medium", "quick_task_label_medium", "quick_task_points_medium"),
    ("heavy", "quick_task_label_heavy", "quick_task_points_heavy"),
    ("super_heavy", "quick_task_label_super_heavy", "quick_task_points_super_heavy"),
]


def ensure_app_settings() -> None:
    for key, value in QUICK_TASK_DEFAULTS.items():
        setting = AppSetting.query.filter_by(key=key).first()
        if not setting:
            db.session.add(AppSetting(key=key, value=str(value)))
    db.session.commit()


def get_setting_int(key: str, default: int) -> int:
    setting = AppSetting.query.filter_by(key=key).first()
    if not setting:
        return default
    try:
        return int(setting.value)
    except (TypeError, ValueError):
        return default


def set_setting_int(key: str, value: int) -> None:
    setting = AppSetting.query.filter_by(key=key).first()
    if not setting:
        setting = AppSetting(key=key, value=str(value))
        db.session.add(setting)
    else:
        setting.value = str(value)


def get_setting_str(key: str, default: str) -> str:
    setting = AppSetting.query.filter_by(key=key).first()
    if not setting or not setting.value.strip():
        return default
    return setting.value.strip()


def set_setting_str(key: str, value: str) -> None:
    setting = AppSetting.query.filter_by(key=key).first()
    normalized = value.strip()
    if not setting:
        setting = AppSetting(key=key, value=normalized)
        db.session.add(setting)
    else:
        setting.value = normalized


def get_quick_task_config() -> dict[str, dict]:
    config: dict[str, dict] = {}
    for effort_key, label_key, points_key in QUICK_TASK_EFFORTS:
        config[effort_key] = {
            "label_key": label_key,
            "label": get_setting_str(label_key, str(QUICK_TASK_DEFAULTS[label_key])),
            "points_key": points_key,
            "points": get_setting_int(points_key, int(QUICK_TASK_DEFAULTS[points_key])),
        }
    return config
