"""Minimal .env read/write — no third-party dependency."""

from __future__ import annotations

from pathlib import Path


def load_dotenv(path: str | Path = ".env") -> None:
    """Set os.environ for keys in `path` that are not already set."""
    import os

    p = Path(path)
    if not p.is_file():
        return
    for line in p.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        if "=" not in line:
            continue
        key, _, value = line.partition("=")
        key = key.strip()
        value = value.strip().strip("'").strip('"')
        if key and key not in os.environ:
            os.environ[key] = value


def upsert_env(path: str | Path, updates: dict[str, str]) -> None:
    """Create or update KEY=value lines; preserve unrelated lines."""
    p = Path(path)
    applied: set[str] = set()
    out_lines: list[str] = []

    if p.is_file():
        for line in p.read_text(encoding="utf-8").splitlines():
            stripped = line.strip()
            if stripped and not stripped.startswith("#") and "=" in stripped:
                k, _, _ = stripped.partition("=")
                k_strip = k.strip()
                matched: tuple[str, str] | None = None
                for uk, uv in updates.items():
                    if uk.lower() == k_strip.lower():
                        matched = (uk, uv)
                        break
                if matched:
                    out_lines.append(f"{matched[0]}={matched[1]}")
                    applied.add(matched[0].lower())
                    continue
            out_lines.append(line)

    for uk, uv in updates.items():
        if uk.lower() not in applied:
            out_lines.append(f"{uk}={uv}")

    text = "\n".join(out_lines)
    if text and not text.endswith("\n"):
        text += "\n"
    p.write_text(text, encoding="utf-8")
