"""Setup-related utilities shared by multiple services."""

from __future__ import annotations

from app.repositories import settings_repo

_KEY_PASSWORD_HASH = "master_password_hash"
_KEY_SETUP_DONE = "setup_completed"
_KEY_MAP_COLOR_THRESHOLD_HIGH = "map_color_threshold_high"
_KEY_MAP_COLOR_THRESHOLD_MEDIUM = "map_color_threshold_medium"
_KEY_MAP_COLOR_THRESHOLD_LOW = "map_color_threshold_low"


async def get_password_hash(db):
    """Return the stored master password hash or None."""
    return await settings_repo.get_setting(db, _KEY_PASSWORD_HASH)


async def get_map_color_thresholds(db):
    """Return map color thresholds as tuple (high, medium, low)."""
    high = await settings_repo.get_setting(db, _KEY_MAP_COLOR_THRESHOLD_HIGH)
    medium = await settings_repo.get_setting(db, _KEY_MAP_COLOR_THRESHOLD_MEDIUM)
    low = await settings_repo.get_setting(db, _KEY_MAP_COLOR_THRESHOLD_LOW)

    return (
        int(high) if high else 100,
        int(medium) if medium else 50,
        int(low) if low else 20,
    )


async def set_map_color_thresholds(
    db,
    *,
    threshold_high: int,
    threshold_medium: int,
    threshold_low: int,
) -> None:
    """Persist map color thresholds after validating values."""
    if threshold_high <= 0 or threshold_medium <= 0 or threshold_low <= 0:
        raise ValueError("All thresholds must be positive integers.")
    if not (threshold_high > threshold_medium > threshold_low):
        raise ValueError("Thresholds must satisfy: high > medium > low.")

    await settings_repo.set_setting(db, _KEY_MAP_COLOR_THRESHOLD_HIGH, str(threshold_high))
    await settings_repo.set_setting(db, _KEY_MAP_COLOR_THRESHOLD_MEDIUM, str(threshold_medium))
    await settings_repo.set_setting(db, _KEY_MAP_COLOR_THRESHOLD_LOW, str(threshold_low))
