# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
"""Parse and serialize hyprsunset.conf profile blocks."""

from __future__ import annotations

import re
from dataclasses import dataclass
from pathlib import Path

_BLOCK_RE = re.compile(r"profile\s*\{(.*?)\}", re.DOTALL)


@dataclass
class Profile:
    time: str = ""
    identity: bool = False
    temperature: int | None = None
    gamma: float | None = None


def _get(body: str, key: str) -> str | None:
    m = re.search(rf"^\s*{key}\s*=\s*(.+?)\s*$", body, re.MULTILINE)
    return m.group(1) if m else None


def parse_config(text: str) -> list[Profile]:
    profiles: list[Profile] = []
    for block in _BLOCK_RE.finditer(text):
        body = block.group(1)
        time = _get(body, "time") or ""
        identity = (_get(body, "identity") or "").lower() == "true"
        temp = _get(body, "temperature")
        gamma = _get(body, "gamma")
        profiles.append(
            Profile(
                time=time,
                identity=identity,
                temperature=int(temp) if temp is not None else None,
                gamma=float(gamma) if gamma is not None else None,
            )
        )
    return profiles


_HEADER = "# Managed by hyprsunset-qt. Edits here are overwritten on save.\n"


def _fmt_gamma(g: float) -> str:
    return f"{g:g}"


def serialize(profiles: list[Profile]) -> str:
    day = day_index(profiles)
    night = night_index(profiles)
    parts = [_HEADER]
    for i, p in enumerate(profiles):
        if i == day:
            parts.append("\n# day profile -- sunrise")
        elif i == night:
            parts.append("\n# night profile -- sunset")
        else:
            parts.append("\n# profile")
        lines = ["profile {", f"    time = {p.time}"]
        if p.identity:
            lines.append("    identity = true")
        if p.temperature is not None:
            lines.append(f"    temperature = {p.temperature}")
        if p.gamma is not None:
            lines.append(f"    gamma = {_fmt_gamma(p.gamma)}")
        lines.append("}")
        parts.append("\n".join(lines))
    return "\n".join(parts) + "\n"


def day_index(profiles: list[Profile]) -> int | None:
    for i, p in enumerate(profiles):
        if p.identity:
            return i
    return None


def night_index(profiles: list[Profile]) -> int | None:
    for i, p in enumerate(profiles):
        if p.temperature is not None:
            return i
    return None


CONFIG_PATH = Path.home() / ".config" / "hypr" / "hyprsunset.conf"


def read_config(path: Path = CONFIG_PATH) -> list[Profile]:
    path = Path(path)
    if not path.exists():
        return []
    return parse_config(path.read_text())


def write_config(profiles: list[Profile], path: Path = CONFIG_PATH) -> None:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(serialize(profiles))


_TIME_RE = re.compile(r"^([01]?\d|2[0-3]):([0-5]\d)$")


def valid_time(s: str) -> bool:
    return bool(_TIME_RE.match(s))


def valid_temperature(t: int) -> bool:
    return 1000 <= t <= 20000


def valid_gamma(g: float) -> bool:
    return 0.0 <= g <= 2.0
