from __future__ import annotations

import os
from typing import Any

from keepedu_performance.api.auth import Principal, unit_allowed
from keepedu_performance.api.repository import Tenant
from keepedu_performance.api.storage import read_json, tenant_root


def _alive_windows(pid: int) -> bool:
    import ctypes
    from ctypes import wintypes

    process_query_limited_information = 0x1000
    still_active = 259
    kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
    kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
    kernel32.OpenProcess.restype = wintypes.HANDLE
    kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, wintypes.LPDWORD]
    kernel32.GetExitCodeProcess.restype = wintypes.BOOL
    kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
    kernel32.CloseHandle.restype = wintypes.BOOL

    handle = kernel32.OpenProcess(process_query_limited_information, False, pid)
    if not handle:
        return False
    try:
        exit_code = wintypes.DWORD()
        if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
            return False
        return exit_code.value == still_active
    finally:
        kernel32.CloseHandle(handle)


def _alive(pid: object) -> bool:
    try:
        identifier = int(pid)
        if os.name == "nt":
            return _alive_windows(identifier)
        os.kill(identifier, 0)
        return True
    except (OSError, TypeError, ValueError):
        return False


def global_status(tenant: Tenant) -> dict[str, Any]:
    dashboard = tenant_root(tenant) / "gold" / "dashboard"
    snapshot = read_json(
        dashboard / f"atualizacao_global_{tenant.year}.json",
        {"anoLetivo": tenant.year, "atualizadoEm": None},
    )
    status = read_json(dashboard / "pipeline_status.json", {})
    running = (
        status.get("ativo") is True
        and status.get("tipo") == "global"
        and _alive(status.get("pid"))
    )
    return snapshot | {
        "emAndamento": running,
        "iniciadoEm": status.get("iniciadoEm") if running else None,
    }


def grade_entry_statuses(tenant: Tenant, principal: Principal) -> dict[str, Any]:
    root = tenant_root(tenant) / "gold"
    statuses = []
    history = root / "atualizacoes_lancamentos" / f"ano={tenant.year}"
    if history.is_dir():
        for path in history.glob("*/data.json"):
            value = read_json(path)
            if value:
                statuses.append(value)
    current = root / "dashboard" / "lancamento_notas" / f"ano={tenant.year}"
    if current.is_dir():
        known = {int(item.get("unidadeId") or -1) for item in statuses}
        for directory in current.glob("unidade=*"):
            try:
                identifier = int(directory.name.removeprefix("unidade="))
            except ValueError:
                continue
            if identifier in known:
                continue
            payloads = [read_json(path) for path in directory.glob("*/data.json")]
            valid = [
                item
                for item in payloads
                if item
                and item.get("generatedAt")
                and (item.get("partition") or {}).get("unidade")
            ]
            if valid:
                oldest = min(str(item["generatedAt"]) for item in valid)
                statuses.append(
                    {
                        "anoLetivo": tenant.year,
                        "unidadeId": identifier,
                        "unidade": valid[0]["partition"]["unidade"],
                        "etapas": {str(stage): oldest for stage in range(1, 5)},
                    }
                )
    statuses = [
        item for item in statuses if unit_allowed(principal, item.get("codcoligada"))
    ]
    return {"items": statuses}
