"""Lightweight push status tracking — stdlib only."""

from __future__ import annotations

import json
import os
import tempfile
import time
from pathlib import Path

PUSH_STATUS_FILE = Path.home() / ".quickcall-trace" / "push_status.json"


def _read_file() -> dict:
    if not PUSH_STATUS_FILE.exists():
        return {}
    try:
        return json.loads(PUSH_STATUS_FILE.read_text())
    except (json.JSONDecodeError, OSError):
        return {}


def _write_file(data: dict) -> None:
    PUSH_STATUS_FILE.parent.mkdir(parents=True, exist_ok=True)
    fd, tmp_path = tempfile.mkstemp(
        dir=PUSH_STATUS_FILE.parent, suffix=".tmp"
    )
    try:
        with os.fdopen(fd, "w") as f:
            json.dump(data, f, indent=2)
        os.replace(tmp_path, PUSH_STATUS_FILE)
    except BaseException:
        try:
            os.unlink(tmp_path)
        except OSError:
            pass
        raise


def record_push(source: str, message_count: int) -> None:
    """Record a successful push for a source."""
    now = time.time()
    data = _read_file()
    data["last_push_at"] = now

    by_source = data.setdefault("by_source", {})
    src = by_source.setdefault(source, {"last_push_at": 0, "messages_pushed": 0})
    src["last_push_at"] = now
    src["messages_pushed"] += message_count

    _write_file(data)


def record_update_check(
    daemon_version: str,
    available_update: str | None = None,
) -> None:
    """Record the result of an auto-update check."""
    data = _read_file()
    data["daemon_version"] = daemon_version
    data["last_update_check"] = time.time()
    if available_update:
        data["available_update"] = available_update
    else:
        data.pop("available_update", None)
    _write_file(data)


def read_push_status() -> dict:
    """Read the push status file."""
    return _read_file()
