#!/usr/bin/env python3
"""Small, offline examples of a persistent cache and an upstream request budget.

The state directory is intentionally supplied by the caller.  This example is
for one local process or a few cooperating demo processes, not a production
client.  ``combined`` runs two independent demonstrations in one directory;
it is not a combined production client.  The clock is fixed for repeatable
output, so use ``--reset`` or a new state directory before repeating a run.
A lock file serializes each read/modify/write transaction.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import tempfile
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Iterator


CACHE_VERSION = 1
BUDGET_VERSION = 1
CACHE_TTL = 3_600
SHORT_WINDOW = 900
DAY = 86_400


@contextmanager
def state_lock(state_dir: Path) -> Iterator[None]:
    """Hold an advisory, cross-platform lock for one state transaction."""

    absolute_dir = Path(os.path.abspath(state_dir))
    for ancestor in (absolute_dir, *absolute_dir.parents):
        if ancestor.is_symlink():
            raise ValueError(f"symlink state directory or ancestor is not allowed: {ancestor}")
    state_dir.mkdir(parents=True, exist_ok=True)
    if state_dir.is_symlink() or not state_dir.is_dir():
        raise ValueError(f"state directory is not a real directory: {state_dir}")
    state_dir.chmod(0o700)  # Windows treats this as a best-effort mode hint.
    lock_path = state_dir / ".demo.lock"
    for known in (lock_path, state_dir / "cache.json", state_dir / "budget.json"):
        if known.is_symlink():
            raise ValueError(f"symlink state path is not allowed: {known}")
        if known.exists() and not known.is_file():
            raise ValueError(f"state path is not a regular file: {known}")
    with lock_path.open("a+b") as handle:
        os.chmod(lock_path, 0o600)  # Windows treats this as a best-effort mode hint.
        handle.seek(0)
        handle.write(b"0")
        handle.flush()
        if os.name == "nt":
            import msvcrt

            handle.seek(0)
            msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
        else:
            import fcntl

            fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
        try:
            yield
        finally:
            if os.name == "nt":
                handle.seek(0)
                msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
            else:
                fcntl.flock(handle.fileno(), fcntl.LOCK_UN)


def read_json(path: Path, default: dict[str, Any]) -> dict[str, Any]:
    if not path.exists():
        return default
    with path.open(encoding="utf-8") as handle:
        value = json.load(handle)
    if not isinstance(value, dict):
        raise ValueError(f"invalid state document: {path}")
    return value


def write_json(path: Path, value: dict[str, Any]) -> None:
    """Atomically replace a state file after the caller has taken the lock."""

    fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump(value, handle, sort_keys=True)
            handle.write("\n")
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(temporary, path)
    finally:
        try:
            os.unlink(temporary)
        except FileNotFoundError:
            pass


def reset_state(state_dir: Path, *, cache: bool, budget: bool) -> None:
    """Remove only the two known state files, while holding the state lock."""

    with state_lock(state_dir):
        for path, selected in ((state_dir / "cache.json", cache), (state_dir / "budget.json", budget)):
            if selected:
                path.unlink(missing_ok=True)


def valid_timestamp(value: Any, now: int) -> bool:
    return isinstance(value, int) and not isinstance(value, bool) and 0 <= value <= now


def validate_conditions(value: Any) -> bool:
    return (
        isinstance(value, dict)
        and set(value) == {"os", "version", "platform"}
        and all(isinstance(item, str) for item in value.values())
    )


def conditions(os_name: str, version: str, platform: str) -> dict[str, str]:
    return {"os": os_name, "version": version, "platform": platform}


def cache_lookup_or_fetch(
    state_dir: Path,
    now: int,
    requested: dict[str, str],
    fetch: Any,
) -> tuple[str, dict[str, Any]]:
    path = state_dir / "cache.json"
    with state_lock(state_dir):
        document = read_json(path, {"version": CACHE_VERSION, "entries": []})
        if set(document) != {"version", "entries"} or document.get("version") != CACHE_VERSION or not isinstance(document.get("entries"), list):
            raise ValueError("invalid cache state")
        entries = document["entries"]
        seen: set[str] = set()
        for entry in entries:
            if (
                not isinstance(entry, dict)
                or set(entry) != {"conditions", "checkedAt", "value"}
                or not validate_conditions(entry["conditions"])
                or not valid_timestamp(entry["checkedAt"], now)
                or not isinstance(entry["value"], dict)
                or entry["value"].get("complete") is not True
            ):
                raise ValueError("invalid cache entry")
            key = json.dumps(entry["conditions"], sort_keys=True)
            if key in seen:
                raise ValueError("duplicate cache conditions")
            seen.add(key)
        for entry in entries:
            if entry.get("conditions") != requested:
                continue
            checked_at = entry.get("checkedAt")
            if not isinstance(checked_at, int):
                raise ValueError("invalid cache timestamp")
            if now - checked_at < CACHE_TTL:
                return "hit", entry
            # Expired records are removed before the new upstream attempt.
            entries.remove(entry)
            break

        try:
            value = fetch()
        except Exception as error:  # demo output keeps the failure observable
            document["entries"] = entries
            write_json(path, document)
            return "fetch_failed", {"error": str(error)}

        if not isinstance(value, dict) or value.get("complete") is not True:
            document["entries"] = entries
            write_json(path, document)
            return "fetch_failed", {"error": "upstream value is incomplete"}
        entry = {"conditions": requested, "checkedAt": now, "value": value}
        entries.append(entry)
        document["entries"] = entries
        write_json(path, document)
        return "fetched", entry


def budget_reserve(state_dir: Path, now: int, short_limit: int = 2, daily_limit: int = 3) -> dict[str, Any]:
    path = state_dir / "budget.json"
    with state_lock(state_dir):
        document = read_json(path, {"version": BUDGET_VERSION, "attempts": []})
        attempts = document.get("attempts")
        if set(document) != {"version", "attempts"} or document.get("version") != BUDGET_VERSION or not isinstance(attempts, list):
            raise ValueError("invalid budget state")
        if any(not valid_timestamp(at, now) for at in attempts):
            raise ValueError("invalid budget timestamp")
        if any(first > second for first, second in zip(attempts, attempts[1:])):
            raise ValueError("budget timestamps must be sorted")
        attempts = [at for at in attempts if now - at < DAY]
        recent = [at for at in attempts if now - at < SHORT_WINDOW]
        retry_after = 0
        if len(recent) >= short_limit:
            retry_after = max(retry_after, recent[0] + SHORT_WINDOW - now)
        if len(attempts) >= daily_limit:
            retry_after = max(retry_after, attempts[0] + DAY - now)
        if retry_after:
            document["attempts"] = attempts
            write_json(path, document)
            return {"allowed": False, "retryAfter": retry_after, "attempts": len(attempts)}
        attempts.append(now)
        document["attempts"] = attempts
        # Reserve and persist before any upstream connection is attempted.
        write_json(path, document)
        return {"allowed": True, "retryAfter": 0, "attempts": len(attempts)}


def upstream_call(state_dir: Path, now: int, label: str, fail: bool) -> dict[str, Any]:
    reservation = budget_reserve(state_dir, now)
    result: dict[str, Any] = {"label": label, "time": now, **reservation}
    if not reservation["allowed"]:
        result["outcome"] = "blocked_before_connection"
    elif fail:
        result["outcome"] = "upstream_failed_but_charged"
    else:
        result["outcome"] = "upstream_succeeded"
    return result


def run_cache(state_dir: Path) -> None:
    base = 1_700_000_000
    linux = conditions("linux", "6.8", "x86_64")
    windows = conditions("windows", "11", "x86_64")

    def fetch() -> dict[str, Any]:
        return {"complete": True, "items": ["fictional-CVE-0001"]}

    events = [
        ("first request", base, linux),
        ("same conditions", base + 10, linux),
        ("different OS", base + 20, windows),
        ("after TTL", base + CACHE_TTL + 1, linux),
    ]
    for label, now, requested in events:
        status, entry = cache_lookup_or_fetch(state_dir, now, requested, fetch)
        print(json.dumps({"event": label, "status": status, "checkedAt": entry.get("checkedAt"), "conditions": requested}, sort_keys=True))


def run_budget(state_dir: Path) -> None:
    base = 1_700_000_000
    for label, now, fail in (
        ("successful request", base, False),
        ("connection failure", base + 1, True),
        ("short window exhausted", base + 2, False),
        ("short window reopened", base + SHORT_WINDOW + 1, False),
        ("daily limit exhausted", base + SHORT_WINDOW * 2 + 2, False),
    ):
        print(json.dumps(upstream_call(state_dir, now, label, fail), sort_keys=True))


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--mode", choices=("cache", "budget", "combined"), default="combined")
    parser.add_argument("--state-dir", type=Path, required=True, help="independent directory for demo JSON state")
    parser.add_argument("--reset", action="store_true", help="remove this demo's state before running")
    args = parser.parse_args()
    if args.reset:
        reset_state(args.state_dir, cache=args.mode in ("cache", "combined"), budget=args.mode in ("budget", "combined"))
    if args.mode in ("cache", "combined"):
        run_cache(args.state_dir)
    if args.mode in ("budget", "combined"):
        run_budget(args.state_dir)
    return 0


if __name__ == "__main__":
    sys.exit(main())
