# retoor <retoor@molodetz.nl>

from __future__ import annotations

import time
from datetime import datetime, timezone

from devplacepy.config import WORKSPACE_ACTIVITY_WRITE_SECONDS
from devplacepy.services.containers import store

_last_write: dict[str, float] = {}
_pending_egress: dict[str, int] = {}
_pending_requests: dict[str, int] = {}


def touch(instance_uid: str, egress_bytes: int = 0) -> None:
    if not instance_uid:
        return
    if egress_bytes > 0:
        _pending_egress[instance_uid] = _pending_egress.get(instance_uid, 0) + egress_bytes
    _pending_requests[instance_uid] = _pending_requests.get(instance_uid, 0) + 1
    now = time.monotonic()
    if now - _last_write.get(instance_uid, 0.0) < WORKSPACE_ACTIVITY_WRITE_SECONDS:
        return
    _last_write[instance_uid] = now
    flush(instance_uid)


def flush(instance_uid: str) -> None:
    egress = _pending_egress.pop(instance_uid, 0)
    requests = _pending_requests.pop(instance_uid, 0)
    store.record_activity(
        instance_uid,
        datetime.now(timezone.utc).isoformat(),
        egress,
        requests,
    )


def flush_all() -> None:
    for instance_uid in list(_pending_requests) + list(_pending_egress):
        if instance_uid in _pending_requests or instance_uid in _pending_egress:
            flush(instance_uid)


def pending(instance_uid: str) -> tuple[int, int]:
    return (
        _pending_egress.get(instance_uid, 0),
        _pending_requests.get(instance_uid, 0),
    )


def forget(instance_uid: str) -> None:
    _last_write.pop(instance_uid, None)
    _pending_egress.pop(instance_uid, None)
    _pending_requests.pop(instance_uid, None)
