from __future__ import annotations

import os
from contextlib import contextmanager
from datetime import datetime, timezone
from typing import Iterator

from keepedu_performance.core.paths import GOLD_DIR
from keepedu_performance.core.update_scope import atomic_write_json


LOCK_PATH = GOLD_DIR.parent / "runtime" / "pipeline.lock"
STATUS_PATH = GOLD_DIR / "dashboard" / "pipeline_status.json"


class PipelineBusyError(RuntimeError):
    pass


def _lock(handle) -> None:
    handle.seek(0)
    if os.name == "nt":
        import msvcrt

        try:
            msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
        except OSError as error:
            raise PipelineBusyError("Ja existe uma atualizacao do painel em andamento.") from error
        return

    import fcntl

    try:
        fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError as error:
        raise PipelineBusyError("Ja existe uma atualizacao do painel em andamento.") from error


def _unlock(handle) -> None:
    handle.seek(0)
    if os.name == "nt":
        import msvcrt

        msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
        return

    import fcntl

    fcntl.flock(handle.fileno(), fcntl.LOCK_UN)


def _status(command: str, active: bool, started_at: str) -> dict:
    return {
        "ativo": active,
        "tipo": "global" if command == "atualizar-tudo" else "direcionada",
        "comando": command,
        "pid": os.getpid(),
        "iniciadoEm": started_at,
        "atualizadoEm": datetime.now(timezone.utc).isoformat(),
    }


@contextmanager
def pipeline_lock(command: str) -> Iterator[None]:
    LOCK_PATH.parent.mkdir(parents=True, exist_ok=True)
    if not LOCK_PATH.exists():
        LOCK_PATH.write_text(" ", encoding="utf-8")
    started_at = datetime.now(timezone.utc).isoformat()
    with LOCK_PATH.open("r+", encoding="utf-8") as handle:
        _lock(handle)
        atomic_write_json(_status(command, True, started_at), STATUS_PATH)
        try:
            yield
        finally:
            atomic_write_json(_status(command, False, started_at), STATUS_PATH)
            _unlock(handle)
