"""Human-readable session slugs derived from request hints."""

from __future__ import annotations

import hashlib
import re
from pathlib import Path

_INLINE_MAX = 80
_DATE_PREFIX = re.compile(r"^\d{4}-\d{2}-\d{2}-")


def normalize_slug_segment(text: str) -> str:
    collapsed = re.sub(r"[^a-z0-9]+", "-", text.lower())
    return collapsed.strip("-")


def slug_base_from_hint(hint: str | None, *, is_path: bool = False) -> str | None:
    if not hint or not hint.strip():
        return None
    raw = hint.strip()
    if is_path:
        stem = _DATE_PREFIX.sub("", Path(raw).name)
        stem = Path(stem).stem
    else:
        stem = raw[:_INLINE_MAX]
    normalized = normalize_slug_segment(stem)
    return normalized or None


def _id_slug_token(adw_id: str) -> str:
    normalized = normalize_slug_segment(adw_id)
    if normalized:
        return normalized
    return hashlib.sha256(adw_id.encode()).hexdigest()[:8]


def workflow_slug_fallback(adw_script_stem: str | None, adw_id: str) -> str:
    stem = (adw_script_stem or "").strip()
    base = normalize_slug_segment(stem.removeprefix("adw_")) if stem else ""
    if not base:
        base = "run"
    return f"{base}-{_id_slug_token(adw_id)}"


def derive_slug_base(
    hint: str | None,
    adw_script_stem: str | None,
    adw_id: str,
    *,
    hint_is_path: bool = False,
) -> str:
    base = slug_base_from_hint(hint, is_path=hint_is_path)
    if base:
        return base
    return workflow_slug_fallback(adw_script_stem, adw_id)


def pick_unique_slug(conn, base: str, *, max_attempts: int = 10_000) -> str:
    for n in range(1, max_attempts + 1):
        candidate = base if n == 1 else f"{base}-{n}"
        row = conn.execute(
            "SELECT 1 FROM sessions WHERE run_slug = ?",
            (candidate,),
        ).fetchone()
        if row is None:
            return candidate
    raise RuntimeError(f"run_slug allocation exhausted for base {base!r}")
