"""Symlink-safe creation helpers for spill/cache files under ``~/.hermes`` (and for our own
dirs in a shared temp root, ``ensure_owned_private_dir``), where a plain
``open(path, "w")`` would follow a pre-planted symlink onto ``~/.bashrc`` etc. New files use
``O_CREAT | O_EXCL`` (fails on ANY existing path, even a dangling link); overwrites ``lstat`` +
``unlink`` first (removes the link, never its target) then create exclusively, so the pair
can't be raced. ``private=True`` (default) = ``0o700`` dirs / ``0o600`` files for spills that
may hold pre-redaction secrets; ``private=False`` keeps umask perms for cache dirs bind-mounted
into remote backends (``credential_files._CACHE_DIRS``). Disk failures raise ``OSError``."""

from __future__ import annotations

import os
import stat
from pathlib import Path
from typing import IO
from hermes_dir_acl import make_user_dir

__all__ = ["ensure_owned_private_dir", "ensure_spill_dir", "open_exclusive", "write_text_exclusive"]

# O_NOFOLLOW is POSIX-only; on Windows O_EXCL alone already refuses every pre-existing path.
_O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)


def ensure_spill_dir(path: Path, *, private: bool = True, keep_group: bool = False) -> Path:
    """Create ``path`` (and parents) as a directory, refusing symlinks. ``private=True``
    creates the leaf ``0o700`` and tightens an existing leaf: to ``0o700``, or with
    ``keep_group=True`` only its world bits go (group bits and setgid stay for a
    shared-group home that already opened the dir up). Raises ``OSError`` if the leaf
    is not a real directory."""
    path = Path(path)
    make_user_dir(path, mode=0o700 if private else 0o777, parents=True, exist_ok=True)
    st = os.lstat(path)
    if not stat.S_ISDIR(st.st_mode):
        raise OSError(f"spill dir is not a directory (symlink?): {path}")
    mode = stat.S_IMODE(st.st_mode)
    want = (mode & ~0o007) if keep_group else 0o700
    if private and mode != want:
        os.chmod(path, want)
    return path


def ensure_owned_private_dir(path: str | os.PathLike) -> str:
    """Create ``path`` ``0o700`` in a SHARED temp root (``/tmp``) and prove it is ours before use.
    Such names are predictable, so ``exist_ok`` alone would adopt a directory another local user
    pre-created (or a symlink they planted) and put our sockets and files inside it. Refuses a
    non-directory or another user's directory with ``PermissionError``; tightens our own dir's
    mode. Owner/mode checks are POSIX-only (Windows has no ``getuid``)."""
    os.makedirs(path, mode=0o700, exist_ok=True)
    st = os.lstat(path)
    if not stat.S_ISDIR(st.st_mode):
        raise PermissionError(f"refusing to use {path}: not a real directory (symlink?)")
    getuid = getattr(os, "getuid", None)
    if getuid is not None:
        if st.st_uid != getuid():
            raise PermissionError(f"refusing to use {path}: owned by another user (uid {st.st_uid})")
        if stat.S_IMODE(st.st_mode) & 0o077:
            os.chmod(path, 0o700)
    return os.fspath(path)


def open_exclusive(path: Path, *, private: bool = True, overwrite: bool = False,
                   encoding: str = "utf-8", errors: str = "strict") -> IO[str]:
    """Open ``path`` for writing via exclusive create; never follows a link. ``overwrite=True``
    first unlinks an existing path (``lstat``-checked, so only the link itself is removed and
    directories are refused), then creates exclusively — the overwrite path cannot be
    redirected through a symlink either."""
    path = Path(path)
    if overwrite:
        try:
            st = os.lstat(path)
        except FileNotFoundError:
            pass
        else:
            if stat.S_ISDIR(st.st_mode):
                raise OSError(f"refusing to overwrite a directory: {path}")
            os.unlink(path)
    mode = 0o600 if private else 0o666  # non-private honors umask
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _O_NOFOLLOW, mode)
    try:
        return os.fdopen(fd, "w", encoding=encoding, errors=errors)
    except Exception:
        os.close(fd)
        raise


def write_text_exclusive(path: Path, text: str, *, private: bool = True, overwrite: bool = False,
                         encoding: str = "utf-8", errors: str = "strict") -> None:
    """``Path.write_text`` equivalent that refuses to follow symlinks."""
    with open_exclusive(path, private=private, overwrite=overwrite, encoding=encoding,
                        errors=errors) as fh:
        fh.write(text)
