"""Persistent state for the patch watcher: last-seen builds, kill switch, failure counter."""
import json
import os
from pathlib import Path

DISABLED_FILENAME = "disabled"
FAILURE_COUNT_FILENAME = "failure-count.txt"


def load_last_seen(path: Path) -> dict:
    if not path.exists():
        return {}
    return json.loads(path.read_text(encoding="utf-8"))


def save_last_seen(path: Path, data: dict) -> None:
    tmp = path.with_suffix(path.suffix + ".tmp")
    tmp.write_text(json.dumps(data, indent=2, sort_keys=True), encoding="utf-8")
    os.replace(tmp, path)


def is_disabled(state_dir: Path) -> bool:
    return (state_dir / DISABLED_FILENAME).exists()


def read_failure_count(state_dir: Path) -> int:
    f = state_dir / FAILURE_COUNT_FILENAME
    if not f.exists():
        return 0
    try:
        return int(f.read_text(encoding="utf-8").strip() or "0")
    except ValueError:
        return 0


def bump_failure(state_dir: Path) -> int:
    n = read_failure_count(state_dir) + 1
    (state_dir / FAILURE_COUNT_FILENAME).write_text(str(n), encoding="utf-8")
    return n


def reset_failures(state_dir: Path) -> None:
    f = state_dir / FAILURE_COUNT_FILENAME
    if f.exists():
        f.unlink()


PENDING_FIXES_FILENAME = "pending-fixes.json"


def _pending_fixes_path(state_dir: Path) -> Path:
    return state_dir / PENDING_FIXES_FILENAME


def load_pending_fixes(state_dir: Path) -> dict:
    p = _pending_fixes_path(state_dir)
    if not p.exists():
        return {}
    return json.loads(p.read_text(encoding="utf-8"))


def record_pending_fix(state_dir: Path, branch: str, entry: dict) -> None:
    fixes = load_pending_fixes(state_dir)
    fixes[branch] = entry
    p = _pending_fixes_path(state_dir)
    tmp = p.with_suffix(p.suffix + ".tmp")
    tmp.write_text(json.dumps(fixes, indent=2, sort_keys=True), encoding="utf-8")
    os.replace(tmp, p)


def remove_pending_fix(state_dir: Path, branch: str) -> None:
    fixes = load_pending_fixes(state_dir)
    if branch not in fixes:
        return
    del fixes[branch]
    p = _pending_fixes_path(state_dir)
    tmp = p.with_suffix(p.suffix + ".tmp")
    tmp.write_text(json.dumps(fixes, indent=2, sort_keys=True), encoding="utf-8")
    os.replace(tmp, p)


PENDING_RELEASES_FILENAME = "pending-releases.json"


def _pending_releases_path(state_dir: Path) -> Path:
    return state_dir / PENDING_RELEASES_FILENAME


def load_pending_releases(state_dir: Path) -> dict:
    p = _pending_releases_path(state_dir)
    if not p.exists():
        return {}
    return json.loads(p.read_text(encoding="utf-8"))


def record_pending_release(state_dir: Path, version: str, entry: dict) -> None:
    releases = load_pending_releases(state_dir)
    releases[version] = entry
    p = _pending_releases_path(state_dir)
    tmp = p.with_suffix(p.suffix + ".tmp")
    tmp.write_text(json.dumps(releases, indent=2, sort_keys=True), encoding="utf-8")
    os.replace(tmp, p)


def remove_pending_release(state_dir: Path, version: str) -> None:
    releases = load_pending_releases(state_dir)
    if version not in releases:
        return
    del releases[version]
    p = _pending_releases_path(state_dir)
    tmp = p.with_suffix(p.suffix + ".tmp")
    tmp.write_text(json.dumps(releases, indent=2, sort_keys=True), encoding="utf-8")
    os.replace(tmp, p)
