"""Boundary's own record of the Docker resources it created, and who may still claim them (E-R2).

**Identities.** Every :class:`OwnershipStore` (one per ``DockerBackend``) has a Boundary-generated
**instance ID**, and every registered run gets an **execution ID**, each 128 bits from
:mod:`secrets` (:func:`new_token`). Neither is ever supplied by or derived from a caller. The
caller's run ID, the audit ID and the configured owner are recorded beside them but are never
proof of ownership.

**The record.** ``work_dir/ownership/instance-<id>.json`` lists every resource this instance
created or verifiably acquired: kind, name, the engine's object ID (and ``CreatedAt`` for
volumes), execution, instance, audit, run, owner and scope. An entry is written as an *intent*
before the create command and completed with the engine's identity afterwards, so a crash between
the two leaves a trail. Each instance writes only its own file, atomically (a temporary file in the
same directory, flushed and ``fsync``-ed, then ``os.replace``), under a thread lock.

**Liveness.** The instance holds an OS-level exclusive lock on ``instance-<id>.lock`` for its whole
life (``msvcrt.locking`` on Windows, ``fcntl.flock`` elsewhere); the operating system releases it
when the process dies, so liveness never depends on a PID. Another instance may treat a record as
recoverable only while it holds that lock itself (:func:`dead_records`).

**Trust.** A record file is trusted only if it parses as this format and version, lies under the
ownership directory (by real path) and names an instance matching its file name. Anything else is
reported and nothing is deleted on its authority. A missing record means "no trust", never
"everything is mine".
"""

from __future__ import annotations

import contextlib
import json
import os
import re
import secrets
import sys
import threading
import weakref
from collections.abc import Iterator
from dataclasses import asdict, dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from typing import IO, Any, Final, Literal

from .plan import LABEL_AUDIT, LABEL_EXECUTION, LABEL_INSTANCE, LABEL_OWNER

RECORD_VERSION: Final = 1
TOKEN_BYTES: Final = 16
TOKEN_RE: Final = re.compile(r"^[0-9a-f]{32}$")
MAX_RECORD_BYTES: Final = 8 * 1024 * 1024
MAX_ENTRIES: Final = 20_000

Kind = Literal["container", "network", "volume", "image"]
State = Literal["intent", "created", "removed"]
Scope = Literal["per_run", "per_audit"]
KINDS: Final = ("container", "network", "volume", "image")
STATES: Final = ("intent", "created", "removed")


def new_token() -> str:
    """128 bits of cryptographic randomness as 32 lowercase hex characters."""
    return secrets.token_hex(TOKEN_BYTES)


# --------------------------------------------------------------------------------------------
# Entries and records
# --------------------------------------------------------------------------------------------
@dataclass
class Entry:
    """One resource this instance created (or verifiably acquired), from intent to verified removal."""

    seq: int
    kind: Kind
    name: str
    instance: str
    owner: str
    audit: str
    run: str | None
    execution: str | None
    scope: Scope | None
    state: State = "intent"
    object_id: str | None = None
    created_at: str | None = None
    note: str | None = None

    def label_identity(self) -> dict[str, str]:
        """The Boundary labels the engine object must carry, exactly, to be this entry's object."""
        labels = {LABEL_INSTANCE: self.instance, LABEL_OWNER: self.owner, LABEL_AUDIT: self.audit}
        if self.execution is not None:
            labels[LABEL_EXECUTION] = self.execution
        return labels

    def describe(self) -> str:
        """``<kind> <engine ID>`` (a volume, or an entry whose ID was never recorded: ``<kind> <name>``)."""
        known = self.object_id not in (None, "never-created") and self.kind != "volume"
        return f"{self.kind} {self.object_id if known else self.name}"


def _untrusted(why: str) -> UntrustedRecordError:
    return UntrustedRecordError(why)


def _text(raw: dict[str, Any], key: str, *, optional: bool, limit: int) -> str | None:
    value = raw.get(key)
    if value is None and optional:
        return None
    if not isinstance(value, str) or not value or len(value) > limit:
        raise _untrusted(f"an entry has an invalid {key}")
    return value


def _entry(raw: Any) -> Entry:
    """One entry, from untrusted JSON data, checked field by field before anything is built."""
    if not isinstance(raw, dict) or set(raw) != set(Entry.__dataclass_fields__):
        raise _untrusted("an entry has missing or unknown fields")
    kind, state, scope, seq = raw.get("kind"), raw.get("state"), raw.get("scope"), raw.get("seq")
    if kind not in KINDS or state not in STATES or scope not in (None, "per_run", "per_audit"):
        raise _untrusted("an entry has an unknown kind, state or scope")
    if not isinstance(seq, int) or isinstance(seq, bool):
        raise _untrusted("an entry has an invalid sequence number")
    required = {key: _text(raw, key, optional=False, limit=256) for key in ("name", "instance", "owner", "audit")}
    optional = {
        key: _text(raw, key, optional=True, limit=512)
        for key in ("run", "execution", "object_id", "created_at", "note")
    }
    if state != "intent" and optional["object_id"] is None:
        raise _untrusted("a created or removed entry has no object identity")
    return Entry(
        seq=seq,
        kind=kind,
        name=str(required["name"]),
        instance=str(required["instance"]),
        owner=str(required["owner"]),
        audit=str(required["audit"]),
        run=optional["run"],
        execution=optional["execution"],
        scope=scope,
        state=state,
        object_id=optional["object_id"],
        created_at=optional["created_at"],
        note=optional["note"],
    )


@dataclass
class Record:
    """One instance's ownership record (the JSON file's content)."""

    instance: str
    owner: str
    entries: list[Entry] = field(default_factory=list)

    def to_json(self) -> str:
        return json.dumps(
            {
                "version": RECORD_VERSION,
                "instance": self.instance,
                "owner": self.owner,
                "entries": [asdict(e) for e in self.entries],
            },
            sort_keys=True,
            indent=1,
        )

    @property
    def open_entries(self) -> list[Entry]:
        return [e for e in self.entries if e.state != "removed"]


class UntrustedRecordError(ValueError):
    """A record file that cannot be trusted as written by a Boundary instance."""


def parse_record(text: str, *, expected_instance: str) -> Record:
    """A :class:`Record` from ``text``; :class:`UntrustedRecordError` for anything unexpected."""
    try:
        data = json.loads(text)
    except ValueError:
        raise _untrusted("the record is not JSON") from None
    if not isinstance(data, dict) or set(data) != {"version", "instance", "owner", "entries"}:
        raise _untrusted("the record has unexpected top-level fields")
    if data["version"] != RECORD_VERSION:
        raise _untrusted("the record has an unknown version")
    instance, owner, raw_entries = data["instance"], data["owner"], data["entries"]
    if instance != expected_instance or not isinstance(instance, str) or not TOKEN_RE.fullmatch(instance):
        raise _untrusted("the record names another instance than its file")
    if not isinstance(owner, str) or not owner:
        raise _untrusted("the record has an invalid owner")
    if not isinstance(raw_entries, list) or len(raw_entries) > MAX_ENTRIES:
        raise _untrusted("the record has invalid entries")
    entries = [_entry(item) for item in raw_entries]
    if any(e.instance != instance or e.owner != owner for e in entries):
        raise _untrusted("an entry belongs to another instance or owner")
    return Record(instance=instance, owner=owner, entries=entries)


# --------------------------------------------------------------------------------------------
# The instance lock (liveness)
# --------------------------------------------------------------------------------------------
def _close(handle: IO[bytes]) -> None:
    """Unlock, then close (closing alone releases the lock only "eventually" on Windows)."""
    with contextlib.suppress(OSError):
        _unlock(handle)
    handle.close()


class InstanceLock:
    """An OS-level exclusive lock on one file, held while this object is open.

    The lock is released by :meth:`release`, when this object is garbage-collected (a dropped
    backend can clean nothing up any more, so its record may then be recovered), and by the OS
    when the process ends however it ends: a killed process never leaves a lock behind.
    """

    def __init__(self, path: Path) -> None:
        self.path = path
        self._handle: IO[bytes] | None = None
        self._finalizer: weakref.finalize[[IO[bytes]], InstanceLock] | None = None

    @property
    def held(self) -> bool:
        return self._handle is not None

    def try_acquire(self) -> bool:
        """Take the lock without waiting; False when another holder (any process) has it."""
        if self._handle is not None:
            return True
        handle = open(self.path, "a+b")  # noqa: SIM115 - held open for the lock's lifetime
        try:
            if not _lock(handle):
                handle.close()
                return False
        except BaseException:
            handle.close()
            raise
        self._handle = handle
        self._finalizer = weakref.finalize(self, _close, handle)
        return True

    def release(self) -> None:
        if self._handle is None or self._finalizer is None:
            return
        self._finalizer()
        self._handle = None
        self._finalizer = None


if sys.platform == "win32":
    import msvcrt

    def _lock(handle: IO[bytes]) -> bool:
        handle.seek(0)
        try:
            msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
        except OSError:
            return False
        return True

    def _unlock(handle: IO[bytes]) -> None:
        handle.seek(0)
        msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)

else:  # pragma: no cover - POSIX (flock); this Windows host runs the msvcrt branch, POSIX is must-prove
    import fcntl

    def _lock(handle: IO[bytes]) -> bool:
        try:
            fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            return False
        return True

    def _unlock(handle: IO[bytes]) -> None:
        fcntl.flock(handle.fileno(), fcntl.LOCK_UN)


# --------------------------------------------------------------------------------------------
# The store
# --------------------------------------------------------------------------------------------
def _write_atomic(path: Path, text: str) -> None:
    temp = path.with_name(f".{path.name}.{new_token()[:12]}.tmp")
    with open(temp, "w", encoding="utf-8", newline="\n") as handle:
        handle.write(text)
        handle.flush()
        os.fsync(handle.fileno())
    os.replace(temp, path)


def record_path(directory: Path, instance: str) -> Path:
    return directory / f"instance-{instance}.json"


def lock_path(directory: Path, instance: str) -> Path:
    return directory / f"instance-{instance}.lock"


class OwnershipStore:
    """This instance's record (in memory and on disk) and its liveness lock."""

    def __init__(self, directory: Path, *, owner: str) -> None:
        self.directory = directory
        directory.mkdir(parents=True, exist_ok=True)
        self.instance = new_token()
        self.owner = owner
        self.record = Record(instance=self.instance, owner=owner)
        self.lock = InstanceLock(lock_path(directory, self.instance))
        if not self.lock.try_acquire():  # pragma: no cover - a fresh 128-bit name is never held
            raise RuntimeError("the new instance's lock is already held")
        self.mutex = threading.RLock()
        self._seq = 0
        self._persist()

    @property
    def path(self) -> Path:
        return record_path(self.directory, self.instance)

    def _persist(self) -> None:
        _write_atomic(self.path, self.record.to_json())

    def intent(
        self,
        kind: Kind,
        name: str,
        *,
        audit: str,
        run: str | None,
        execution: str | None,
        scope: Scope | None = None,
    ) -> Entry:
        """Write the intent to create ``name`` (before the create command runs)."""
        with self.mutex:
            self._seq += 1
            entry = Entry(
                seq=self._seq,
                kind=kind,
                name=name,
                instance=self.instance,
                owner=self.owner,
                audit=audit,
                run=run,
                execution=execution,
                scope=scope,
                note=f"intent {datetime.now(UTC).isoformat(timespec='seconds')}",
            )
            self.record.entries.append(entry)
            self._persist()
            return entry

    def created(self, entry: Entry, object_id: str, created_at: str | None = None) -> None:
        """Complete an intent with the engine's identity of the object."""
        with self.mutex:
            entry.object_id = object_id
            entry.created_at = created_at
            entry.state = "created"
            entry.note = None
            self._persist()

    def removed(self, entry: Entry, note: str) -> None:
        """Mark an entry verified gone (or never created)."""
        with self.mutex:
            entry.state = "removed"
            entry.note = note[:200]
            if entry.object_id is None:
                entry.object_id = "never-created"
            self._persist()

    def entries(self) -> list[Entry]:
        with self.mutex:
            return list(self.record.entries)

    def close(self) -> None:
        """Release the liveness lock; the record files go only when every entry is verified removed."""
        with self.mutex:
            if not self.record.open_entries:
                with contextlib.suppress(OSError):
                    self.path.unlink()
            self.lock.release()
            if not self.record.open_entries:
                with contextlib.suppress(OSError):
                    self.lock.path.unlink()


# --------------------------------------------------------------------------------------------
# Other instances' records
# --------------------------------------------------------------------------------------------
@dataclass
class ForeignRecord:
    """Another instance's record as found on disk, with what this instance may do with it."""

    instance: str
    path: Path
    status: Literal["dead", "alive", "untrusted", "other-owner"]
    reason: str = ""
    record: Record | None = None
    lock: InstanceLock | None = None

    def persist(self) -> None:
        if self.record is not None and self.lock is not None and self.lock.held:
            _write_atomic(self.path, self.record.to_json())

    def finish(self) -> None:
        """Keep the record if anything is left; otherwise delete it, then its lock file."""
        if self.lock is None:
            return
        try:
            if self.record is not None and self.lock.held and not self.record.open_entries:
                with contextlib.suppress(OSError):
                    self.path.unlink()
                self.lock.release()
                with contextlib.suppress(OSError):
                    lock_path(self.path.parent, self.instance).unlink()
            else:
                self.persist()
        finally:
            self.lock.release()


_RECORD_NAME: Final = re.compile(r"^instance-([0-9a-f]{32})\.json$")


def _read_record(path: Path, instance: str) -> Record:
    if path.stat().st_size > MAX_RECORD_BYTES:
        raise _untrusted("the record file is too large")
    return parse_record(path.read_text(encoding="utf-8"), expected_instance=instance)


def foreign_records(directory: Path, *, own_instance: str, owner: str) -> Iterator[ForeignRecord]:
    """Every other instance's record in ``directory``, classified; a dead one is yielded with its lock held.

    Only a record whose owner is ``owner`` **and** whose instance lock this process can take is
    ``dead`` (recoverable). The caller must call :meth:`ForeignRecord.finish` on each dead one.
    """
    if not directory.is_dir():
        return
    root = Path(os.path.realpath(directory))
    for path in sorted(directory.iterdir()):
        match = _RECORD_NAME.fullmatch(path.name)
        if match is None or match.group(1) == own_instance:
            continue
        instance = match.group(1)
        real = Path(os.path.realpath(path))
        if real.parent != root or path.is_symlink() or not real.is_file():
            yield ForeignRecord(instance, path, "untrusted", "the record file is out of place or not a regular file")
            continue
        lock = InstanceLock(lock_path(directory, instance))
        if not lock.try_acquire():
            alive = None
            with contextlib.suppress(UntrustedRecordError, OSError, UnicodeDecodeError):
                alive = _read_record(real, instance)  # read only, to name what a live instance owns
            yield ForeignRecord(instance, path, "alive", "its instance is alive (its lock is held)", record=alive)
            continue
        try:
            record = _read_record(real, instance)
        except (UntrustedRecordError, OSError, UnicodeDecodeError) as exc:
            lock.release()
            yield ForeignRecord(instance, path, "untrusted", f"the record cannot be trusted ({str(exc)[:120]})")
            continue
        if record.owner != owner:
            lock.release()
            yield ForeignRecord(instance, path, "other-owner", "the record belongs to another owner", record=record)
            continue
        yield ForeignRecord(instance, path, "dead", "", record=record, lock=lock)
