"""Unnamed-inode bootstrap publication for the fixed registration registry."""

from __future__ import annotations

import errno
import hashlib
import os
import stat
from dataclasses import dataclass
from typing import Final

from checkin_cli.weekly_operations import (
    WeeklyOperationsAuthorityCompromise,
    WeeklyOperationsCorruption,
    WeeklyOperationsPlatformNotSupported,
)
from checkin_cli.weekly_operations_canonical_registry_history import REGISTRY_NAME
from checkin_cli.weekly_operations_link import link_unnamed_file
from checkin_cli.weekly_operations_parent import WeeklyOperationsParentAuthority

EMPTY_REGISTRY_DIGEST: Final = hashlib.sha256(b"").hexdigest()
_UNSUPPORTED: Final = frozenset((errno.ENOSYS, errno.EOPNOTSUPP, errno.EINVAL, errno.EPERM))


@dataclass(frozen=True, slots=True)
class PreparedRegistry:
    descriptor: int
    identity: tuple[int, int]
    info: os.stat_result


def _safe(info: os.stat_result, links: int) -> bool:
    return (
        stat.S_ISREG(info.st_mode)
        and stat.S_IMODE(info.st_mode) == 0o600
        and info.st_uid == os.geteuid()
        and info.st_nlink == links
        and info.st_size == 0
    )


def prepare_registry(parent: WeeklyOperationsParentAuthority) -> PreparedRegistry:
    parent.verify()
    if os.listdir(parent.descriptor):
        raise WeeklyOperationsCorruption("uninitialized authority directory is not empty")
    try:
        descriptor = os.open(
            ".", os.O_TMPFILE | os.O_RDWR | os.O_CLOEXEC, 0o600,
            dir_fd=parent.descriptor,
        )
    except OSError as error:
        if error.errno in _UNSUPPORTED:
            raise WeeklyOperationsPlatformNotSupported(
                "O_TMPFILE registry publication is unsupported"
            ) from error
        raise WeeklyOperationsCorruption("unnamed registry creation failed") from error
    try:
        os.fsync(descriptor)
        info = os.fstat(descriptor)
        if not _safe(info, 0):
            raise WeeklyOperationsAuthorityCompromise("unnamed registry is unsafe")
        return PreparedRegistry(descriptor, (info.st_dev, info.st_ino), info)
    except (OSError, WeeklyOperationsCorruption, KeyboardInterrupt, SystemExit):
        os.close(descriptor)
        raise


def reconcile_registry(directory: int, prepared: PreparedRegistry) -> os.stat_result:
    try:
        descriptor = os.open(
            REGISTRY_NAME,
            os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW | os.O_CLOEXEC,
            dir_fd=directory,
        )
    except OSError as error:
        raise WeeklyOperationsAuthorityCompromise("bootstrap registry name is unsafe") from error
    try:
        info = os.fstat(descriptor)
        named = os.stat(REGISTRY_NAME, dir_fd=directory, follow_symlinks=False)
        if (
            not _safe(info, 1)
            or (info.st_dev, info.st_ino) != prepared.identity
            or prepared.identity != (named.st_dev, named.st_ino)
        ):
            raise WeeklyOperationsAuthorityCompromise("bootstrap registry identity changed")
        return info
    finally:
        os.close(descriptor)


def commit_registry(
    parent: WeeklyOperationsParentAuthority, prepared: PreparedRegistry
) -> os.stat_result:
    try:
        link_unnamed_file(prepared.descriptor, parent.descriptor, REGISTRY_NAME)
    except FileExistsError as error:
        raise WeeklyOperationsAuthorityCompromise("bootstrap registry name occupied") from error
    except OSError as error:
        raise WeeklyOperationsCorruption("bootstrap registry link failed") from error
    try:
        os.fsync(parent.descriptor)
    except OSError as error:
        raise WeeklyOperationsCorruption("registry directory fsync failed") from error
    return reconcile_registry(parent.descriptor, prepared)


def remove_owned_registry(parent: WeeklyOperationsParentAuthority, prepared: PreparedRegistry) -> None:
    try:
        info = os.stat(REGISTRY_NAME, dir_fd=parent.descriptor, follow_symlinks=False)
    except FileNotFoundError:
        return
    if (info.st_dev, info.st_ino) != prepared.identity:
        raise WeeklyOperationsAuthorityCompromise(
            "unowned bootstrap registry substitution preserved"
        )
    os.unlink(REGISTRY_NAME, dir_fd=parent.descriptor)
    os.fsync(parent.descriptor)
