"""Read/write ``config.toml`` (stdlib only)."""
from __future__ import annotations

import re
import tomllib
from pathlib import Path

ROOT = Path(__file__).resolve().parent
CONFIG_PATH = ROOT / "config.toml"


def load_config() -> dict:
    if not CONFIG_PATH.exists():
        return {}
    with CONFIG_PATH.open("rb") as handle:
        return tomllib.load(handle)


def _format_value(value: int | float | str | bool) -> str:
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, float):
        return str(int(value)) if value.is_integer() else repr(value)
    if isinstance(value, int):
        return str(value)
    return repr(value)


def _set_section_values(section: str, updates: dict[str, int | float | str | bool]) -> None:
    lines = CONFIG_PATH.read_text(encoding="utf-8").splitlines() if CONFIG_PATH.exists() else []
    if not lines:
        lines = [f"[{section}]"]

    in_section = False
    written: set[str] = set()
    out: list[str] = []

    def flush_missing() -> None:
        for key, value in updates.items():
            if key not in written:
                out.append(f"{key} = {_format_value(value)}")
                written.add(key)

    for line in lines:
        stripped = line.strip()
        if stripped.startswith("[") and stripped.endswith("]"):
            if in_section:
                flush_missing()
            in_section = stripped == f"[{section}]"
            out.append(line)
            continue

        if in_section:
            matched = False
            for key, value in updates.items():
                if re.match(rf"^{re.escape(key)}\s*=", stripped):
                    out.append(f"{key} = {_format_value(value)}")
                    written.add(key)
                    matched = True
                    break
            if not matched:
                out.append(line)
        else:
            out.append(line)

    if in_section:
        flush_missing()
    elif section not in {ln.strip() for ln in lines if ln.strip().startswith("[")}:
        out.append(f"[{section}]")
        flush_missing()

    CONFIG_PATH.write_text("\n".join(out).rstrip() + "\n", encoding="utf-8")


def _remove_section_keys(section: str, keys: tuple[str, ...]) -> None:
    if not CONFIG_PATH.exists():
        return
    remove = set(keys)
    out: list[str] = []
    in_section = False
    for line in CONFIG_PATH.read_text(encoding="utf-8").splitlines():
        stripped = line.strip()
        if stripped.startswith("[") and stripped.endswith("]"):
            in_section = stripped == f"[{section}]"
            out.append(line)
            continue
        if in_section and any(re.match(rf"^{re.escape(key)}\s*=", stripped) for key in remove):
            continue
        out.append(line)
    CONFIG_PATH.write_text("\n".join(out).rstrip() + "\n", encoding="utf-8")


def save_window_margins(margin_right: int, margin_above_taskbar: int) -> None:
    _set_section_values(
        "display",
        {
            "margin_right": int(margin_right),
            "margin_above_taskbar": int(margin_above_taskbar),
        },
    )
    _remove_section_keys("display", ("position_x", "position_y"))
