"""Worker enrollment token issuance and validation."""

from __future__ import annotations

import hashlib
import secrets
import uuid

from fastapi import HTTPException

from hive_compute.coordinator.database import get_db_ctx


def create_enrollment_token(
    admin_user_id: str,
    label: str | None = None,
    ttl_minutes: int = 60,
    max_uses: int = 1,
) -> dict:
    """Mint a short-lived worker enrollment token and persist only its hash."""
    token_id = f"enroll_{uuid.uuid4().hex[:12]}"
    token = f"henr_{secrets.token_urlsafe(18)}"

    with get_db_ctx() as db:
        db.execute(
            """
            INSERT INTO worker_enrollment_tokens
                (token_id, token_hash, label, created_by_admin_user_id, expires_at, max_uses)
            VALUES (?, ?, ?, ?, datetime('now', ?), ?)
            """,
            (
                token_id,
                _hash_token(token),
                label.strip() if label else None,
                admin_user_id,
                f"+{ttl_minutes} minutes",
                max_uses,
            ),
        )
        row = db.execute(
            """
            SELECT
                token_id,
                label,
                expires_at,
                max_uses,
                used_count,
                revoked_at,
                created_at
            FROM worker_enrollment_tokens
            WHERE token_id = ?
            """,
            (token_id,),
        ).fetchone()

    return {
        "tokenId": row["token_id"],
        "token": token,
        "label": row["label"],
        "expiresAt": row["expires_at"],
        "maxUses": row["max_uses"],
        "usedCount": row["used_count"],
        "revokedAt": row["revoked_at"],
        "createdAt": row["created_at"],
    }


def list_enrollment_tokens() -> list[dict]:
    """List enrollment token metadata without exposing raw token material."""
    with get_db_ctx() as db:
        rows = db.execute(
            """
            SELECT
                token_id,
                label,
                created_by_admin_user_id,
                created_at,
                expires_at,
                max_uses,
                used_count,
                last_used_at,
                last_used_by_worker_id,
                revoked_at
            FROM worker_enrollment_tokens
            ORDER BY created_at DESC
            """
        ).fetchall()

    return [
        {
            "tokenId": row["token_id"],
            "label": row["label"],
            "createdByAdminUserId": row["created_by_admin_user_id"],
            "createdAt": row["created_at"],
            "expiresAt": row["expires_at"],
            "maxUses": row["max_uses"],
            "usedCount": row["used_count"],
            "lastUsedAt": row["last_used_at"],
            "lastUsedByWorkerId": row["last_used_by_worker_id"],
            "revokedAt": row["revoked_at"],
            "status": _get_token_status(row),
        }
        for row in rows
    ]


def revoke_enrollment_token(token_id: str) -> bool:
    """Revoke an existing enrollment token."""
    with get_db_ctx() as db:
        result = db.execute(
            """
            UPDATE worker_enrollment_tokens
            SET revoked_at = datetime('now')
            WHERE token_id = ? AND revoked_at IS NULL
            """,
            (token_id,),
        )
    return result.rowcount > 0


def consume_enrollment_token(token: str, worker_id: str) -> dict:
    """Consume one use of an active enrollment token."""
    token_hash = _hash_token(token)

    with get_db_ctx() as db:
        row = db.execute(
            """
            SELECT token_id
            FROM worker_enrollment_tokens
            WHERE token_hash = ?
              AND revoked_at IS NULL
              AND expires_at > datetime('now')
              AND used_count < max_uses
            """,
            (token_hash,),
        ).fetchone()
        if not row:
            raise HTTPException(status_code=401, detail="Invalid or expired enrollment token")

        result = db.execute(
            """
            UPDATE worker_enrollment_tokens
            SET used_count = used_count + 1,
                last_used_at = datetime('now'),
                last_used_by_worker_id = ?
            WHERE token_id = ?
              AND revoked_at IS NULL
              AND expires_at > datetime('now')
              AND used_count < max_uses
            """,
            (worker_id, row["token_id"]),
        )
        if result.rowcount == 0:
            raise HTTPException(status_code=401, detail="Invalid or expired enrollment token")

    return {"tokenId": row["token_id"], "authType": "enrollment_token"}


def _get_token_status(row) -> str:
    if row["revoked_at"]:
        return "revoked"
    if row["used_count"] >= row["max_uses"]:
        return "used"
    from datetime import UTC, datetime

    try:
        expires = datetime.fromisoformat(row["expires_at"]).replace(tzinfo=UTC)
        if expires < datetime.now(UTC):
            return "expired"
    except (ValueError, TypeError):
        pass
    return "active"


def _hash_token(token: str) -> str:
    return hashlib.sha256(token.encode()).hexdigest()
