from __future__ import annotations

import secrets
from datetime import datetime
import re


_USER_SAFE_RE = re.compile(r"[^a-z0-9_-]+")


def _normalize_user_id(user_id: str) -> str:
    s = (user_id or "").strip().lower()
    s = _USER_SAFE_RE.sub("-", s)
    s = re.sub(r"-{2,}", "-", s).strip("-")
    return s[:24] if s else ""


def new_task_id(workload: str, *, user_id: str | None = None) -> str:
    ts = datetime.now().strftime("%Y%m%d-%H%M%S")
    suffix = secrets.token_hex(2)
    u = _normalize_user_id(user_id or "")
    if u:
        return f"mvp2-{u}-{workload}-{ts}-{suffix}"
    return f"mvp2-{workload}-{ts}-{suffix}"


def attempt_submission_id(task_id: str, attempt_no: int) -> str:
    return f"{task_id}--a{attempt_no:02d}"


def new_model_key(*, user_id: str) -> str:
    """
    Internal identifier for a serving model record.

    Note:
    - model_id is the OpenAI-facing name (user_id + timestamp prefix + suffix).
    - model_key is used for stable DB identity and API resource path.
    """
    ts = datetime.now().strftime("%Y%m%d-%H%M%S")
    suffix = secrets.token_hex(2)
    u = _normalize_user_id(user_id)
    if not u:
        raise ValueError("user_id is required")
    return f"mvp2-{u}-serve-{ts}-{suffix}"
