"""Crash-safe publication of a complete graph/index generation.

The active graph is selected by the small ``CURRENT`` pointer file.  Writers
build a complete generation in a temporary directory and only advance the
pointer after every artifact and the manifest have been written successfully.
Legacy flat graph directories remain readable when no pointer exists.
"""
from __future__ import annotations

import hashlib
import json
import logging
import os
import shutil
import threading
import time
import uuid
from contextlib import contextmanager
from pathlib import Path, PurePosixPath
from typing import Any, Callable


GRAPH_SCHEMA_VERSION = 11

_LOCKS_GUARD = threading.Lock()
_PROCESS_LOCKS: dict[str, threading.Lock] = {}
logger = logging.getLogger(__name__)


def _atomic_replace_dir(src: Path, dst: Path) -> None:
    """Rename *src* to *dst* with retry, tolerating transient Windows locks.

    On Windows, ``os.replace`` on a directory can fail with ``PermissionError
    [WinError 5]`` when an external process (antivirus real-time scan, search
    indexer, or a just-released handle inside the tree) briefly holds the
    directory or one of its children.  Such failures are transient: a short
    backoff and retry almost always succeeds.  We retry for up to ~1s before
    surfacing the error, which keeps generation publication robust under heavy
    watcher churn without weakening atomicity (each attempt is still a single
    atomic rename; only the timing changes).
    """
    delays = (0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.37)  # ~1.0s total
    last_exc: Exception | None = None
    for i, delay in enumerate(delays):
        try:
            os.replace(src, dst)
            return
        except PermissionError as exc:
            last_exc = exc
            # WinError 5 (access denied) is the transient case we retry on.
            # Other PermissionErrors are unlikely for a rename but retry once
            # anyway — surfacing a false failure is worse than a tiny delay.
            if i < len(delays) - 1:
                time.sleep(delay)
        except OSError as exc:
            # On Windows, WinError 5 surfaces as PermissionError; on some
            # configurations a sharing violation can come through as a plain
            # OSError. Retry transient ones.
            last_exc = exc
            if i < len(delays) - 1 and getattr(exc, "winerror", None) in (5, 32):
                time.sleep(delay)
            else:
                raise
    assert last_exc is not None
    raise last_exc


class GenerationRepository:
    FORMAT_VERSION = 1

    def __init__(self, root: str | Path, keep: int = 2):
        self.root = Path(root)
        self.generations = self.root / "generations"
        self.current_file = self.root / "CURRENT"
        self.keep = max(2, keep)
        self._cleanup_orphan_tmp()

    def _cleanup_orphan_tmp(self) -> None:
        """Remove stale ``.tmp`` staging directories left by failed publishes.

        A ``.tmp`` directory is orphaned when a publish crashes before
        ``os.replace``.  These are not counted in retention and accumulate
        indefinitely.  We remove any ``.tmp`` older than 1 hour (to avoid
        deleting a directory that is actively being written by another
        process).
        """
        try:
            if not self.generations.is_dir():
                return
            import time as _time
            cutoff = _time.time() - 3600  # 1 hour
            for p in self.generations.iterdir():
                if not p.is_dir() or not p.name.endswith(".tmp"):
                    continue
                try:
                    mtime = p.stat().st_mtime
                    if mtime < cutoff:
                        shutil.rmtree(p, ignore_errors=True)
                        logger.info("Removed orphan staging directory: %s", p.name)
                except OSError:
                    pass
        except OSError:
            pass

    def cleanup_staging(self) -> None:
        """Remove all ``.tmp`` staging directories immediately.

        Unlike ``_cleanup_orphan_tmp`` (which only removes directories older
        than 1 hour), this removes ALL staging directories.  Called during
        server shutdown to prevent accumulation from interrupted publishes.
        Safe because staging directories are only created during an active
        publish, and this is called after the watcher has stopped.
        """
        try:
            if not self.generations.is_dir():
                return
            for p in self.generations.iterdir():
                if p.is_dir() and p.name.endswith(".tmp"):
                    shutil.rmtree(p, ignore_errors=True)
                    logger.info("Cleaned up staging directory: %s", p.name)
        except OSError:
            pass

    def current_generation(self) -> str | None:
        try:
            generation = self.current_file.read_text(encoding="utf-8").strip()
        except (OSError, UnicodeError):
            return None
        return generation or None

    def current_path(self) -> Path:
        """Return the latest complete generation, or the legacy root."""
        generation = self.current_generation()
        if generation:
            candidate = self.generations / generation
            if self._is_complete(candidate, generation):
                return candidate

        # Recover from a corrupt/missing CURRENT pointer by selecting the most
        # recent complete generation.  Temporary directories are ignored.
        try:
            candidates = sorted(
                (
                    p
                    for p in self.generations.iterdir()
                    if p.is_dir() and not p.name.endswith(".tmp")
                ),
                key=lambda p: p.name,
                reverse=True,
            )
        except OSError:
            candidates = []
        if candidates:
            for candidate in candidates:
                if self._is_complete(candidate, candidate.name):
                    return candidate
        return self.root

    def current_manifest(self) -> dict[str, Any] | None:
        """Return the validated active manifest, if generations are in use."""
        current = self.current_path()
        if current == self.root:
            return None
        try:
            manifest = json.loads(
                (current / "manifest.json").read_text(encoding="utf-8")
            )
        except (OSError, UnicodeError, ValueError, TypeError):
            return None
        return manifest if isinstance(manifest, dict) else None

    def publish(
        self,
        writer: Callable[[Path], None],
        metadata: dict[str, Any] | None = None,
    ) -> Path:
        """Write and atomically publish one complete generation."""
        self.root.mkdir(parents=True, exist_ok=True)
        self.generations.mkdir(parents=True, exist_ok=True)
        generation = f"{time.time_ns():020d}-{uuid.uuid4().hex[:8]}"
        staging = self.generations / f"{generation}.tmp"
        final = self.generations / generation
        staging.mkdir(parents=False, exist_ok=False)
        current_switched = False

        try:
            writer(staging)
            artifacts = self._artifact_manifest(staging)
            manifest = {
                "format_version": self.FORMAT_VERSION,
                "generation": generation,
                "created_at": time.time(),
                "metadata": metadata or {},
                "artifacts": artifacts,
            }
            self._atomic_write_json(staging / "manifest.json", manifest)
            with self._publication_lock():
                _atomic_replace_dir(staging, final)
                try:
                    self._atomic_write_text(self.current_file, generation + "\n")
                except BaseException:
                    # The generation is not reachable until CURRENT advances.
                    # Remove the renamed staging directory before surfacing the
                    # failure so callers can safely retain the prior state.
                    shutil.rmtree(final, ignore_errors=True)
                    raise
                current_switched = True
                try:
                    self._cleanup_old_generations(exclude={generation})
                except BaseException:
                    # CURRENT is the publication commit point.  Once it has
                    # advanced, cleanup is housekeeping and must never make a
                    # successful publication look failed to the caller.
                    logger.warning(
                        "Published generation %s, but old-generation cleanup failed",
                        generation,
                        exc_info=True,
                    )
        except BaseException:
            if current_switched:
                # This also protects against an exceptional lock-release path
                # after the pointer has committed.
                logger.warning(
                    "Published generation %s, but post-publication housekeeping failed",
                    generation,
                    exc_info=True,
                )
                return final
            shutil.rmtree(staging, ignore_errors=True)
            # ``staging`` may already have been atomically renamed to ``final``
            # before CURRENT failed.
            shutil.rmtree(final, ignore_errors=True)
            raise
        return final

    def publish_graph_state(
        self,
        store: Any,
        keyword_index: Any,
        semantic_index: Any = None,
        metadata: dict[str, Any] | None = None,
    ) -> Path:
        """Publish one self-contained JSON graph and its search indexes.

        ``GenerationRepository`` deliberately remains storage-agnostic, while
        this convenience method defines the artifact set used by the JSON
        backend.  The core files are checked before ``CURRENT`` can advance;
        semantic artifacts are included whenever a semantic index is active.
        """

        def write(staging: Path) -> None:
            store.save(str(staging))
            keyword_index.save(staging)
            if semantic_index is not None:
                semantic_index.save(str(staging))

            required = ("nodes.json", "edges.json", "keyword_index.json")
            missing = [name for name in required if not (staging / name).is_file()]
            if missing:
                raise RuntimeError(
                    "Incomplete JSON graph generation; missing: "
                    + ", ".join(missing)
                )

        graph_metadata = dict(metadata or {})
        graph_metadata["artifact_profile"] = "json_graph_v1"
        return self.publish(write, metadata=graph_metadata)

    def validate(self, path: str | Path) -> bool:
        path = Path(path)
        return self._is_complete(path, path.name)

    def _is_complete(self, directory: Path, generation: str) -> bool:
        manifest_file = directory / "manifest.json"
        try:
            manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
        except (OSError, UnicodeError, ValueError, TypeError):
            return False
        if not isinstance(manifest, dict):
            return False
        if manifest.get("format_version") != self.FORMAT_VERSION:
            return False
        if manifest.get("generation") != generation:
            return False
        artifacts = manifest.get("artifacts")
        if not isinstance(artifacts, dict) or not artifacts:
            return False
        metadata = manifest.get("metadata", {})
        if not isinstance(metadata, dict):
            return False
        if (
            (
                metadata.get("storage_backend") == "json"
                or metadata.get("artifact_profile") == "json_graph_v1"
            )
            and not {"nodes.json", "edges.json", "keyword_index.json"}.issubset(
                artifacts
            )
        ):
            return False
        try:
            resolved_directory = directory.resolve(strict=False)
        except (OSError, RuntimeError):
            return False
        for rel, expected in artifacts.items():
            if not isinstance(rel, str) or not isinstance(expected, dict):
                return False
            normalized_rel = rel.replace("\\", "/")
            rel_path = PurePosixPath(normalized_rel)
            if (
                not normalized_rel
                or rel_path.is_absolute()
                or ".." in rel_path.parts
                or rel_path.as_posix() != normalized_rel
            ):
                return False
            size = expected.get("size")
            checksum = expected.get("sha256")
            if not isinstance(size, int) or isinstance(size, bool) or size < 0:
                return False
            if not isinstance(checksum, str):
                return False
            artifact = directory.joinpath(*rel_path.parts)
            try:
                artifact.resolve(strict=False).relative_to(resolved_directory)
            except (OSError, RuntimeError, ValueError):
                return False
            if not artifact.is_file():
                return False
            try:
                if artifact.stat().st_size != size:
                    return False
                if self._sha256(artifact) != checksum:
                    return False
            except OSError:
                return False
        return True

    def _artifact_manifest(self, directory: Path) -> dict[str, dict[str, Any]]:
        artifacts: dict[str, dict[str, Any]] = {}
        for path in sorted(p for p in directory.rglob("*") if p.is_file()):
            rel = path.relative_to(directory).as_posix()
            artifacts[rel] = {"size": path.stat().st_size, "sha256": self._sha256(path)}
        return artifacts

    @staticmethod
    def _sha256(path: Path) -> str:
        digest = hashlib.sha256()
        with path.open("rb") as stream:
            for chunk in iter(lambda: stream.read(1024 * 1024), b""):
                digest.update(chunk)
        return digest.hexdigest()

    @staticmethod
    def _atomic_write_text(path: Path, content: str) -> None:
        path.parent.mkdir(parents=True, exist_ok=True)
        tmp = path.with_name(path.name + f".{uuid.uuid4().hex}.tmp")
        try:
            tmp.write_text(content, encoding="utf-8")
            os.replace(tmp, path)
        except BaseException:
            try:
                tmp.unlink(missing_ok=True)
            except OSError:
                pass
            raise

    @classmethod
    def _atomic_write_json(cls, path: Path, payload: dict[str, Any]) -> None:
        cls._atomic_write_text(path, json.dumps(payload, ensure_ascii=False, indent=2))

    def _cleanup_old_generations(self, exclude: set[str]) -> None:
        candidates = sorted(
            (
                p for p in self.generations.iterdir()
                if p.is_dir() and not p.name.endswith(".tmp") and p.name not in exclude
            ),
            key=lambda p: p.name,
            reverse=True,
        )
        complete: list[Path] = []
        for candidate in candidates:
            if self._is_complete(candidate, candidate.name):
                complete.append(candidate)
                continue
            # Corrupt or incomplete generations cannot be recovery candidates
            # and therefore must not consume one of the retention slots.
            shutil.rmtree(candidate)
        for old in complete[self.keep - 1 :]:
            # Publication treats CURRENT as the commit point and converts any
            # cleanup error into a warning.  Do not hide the failure here or it
            # would be impossible to diagnose accumulating stale generations.
            shutil.rmtree(old)

    @contextmanager
    def _publication_lock(self):
        """Serialize finalize/CURRENT/cleanup across threads and processes."""
        key = str(self.root.resolve())
        with _LOCKS_GUARD:
            thread_lock = _PROCESS_LOCKS.setdefault(key, threading.Lock())
        with thread_lock:
            self.root.mkdir(parents=True, exist_ok=True)
            lock_path = self.root / ".publish.lock"
            with lock_path.open("a+b") as lock_file:
                if os.name == "nt":
                    import msvcrt

                    if lock_file.tell() == 0:
                        lock_file.write(b"\0")
                        lock_file.flush()
                    lock_file.seek(0)
                    msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1)
                    try:
                        yield
                    finally:
                        lock_file.seek(0)
                        msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)
                else:
                    import fcntl

                    fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
                    try:
                        yield
                    finally:
                        fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)