"""Utilities for tracking and resolving user-facing task reference receipts.

Kyber exposes short cryptographic receipts (e.g. "⚡a3f1b2c4", "✅b7e2d9f1")
to users so they can ask for status updates. Internally, SubagentManager uses
an 8-char task_id (uuid prefix). This module bridges the two.
"""

from __future__ import annotations

import re
from dataclasses import dataclass, field


_HEX8_RE = re.compile(r"(?i)\b[0-9a-f]{8}\b")


def normalize_task_ref(value: str) -> str | None:
    """Normalize a user-provided reference string to its bare 8-hex token.

    Accepts:
    - "⚡a3f1b2c4" / "✅a3f1b2c4"
    - "a3f1b2c4"
    - Any string containing a standalone 8-hex token.
    """
    if not value:
        return None

    v = value.strip()
    if not v:
        return None

    # Fast-path: emoji-prefixed receipts
    if (v.startswith("⚡") or v.startswith("✅")) and len(v) >= 9:
        cand = v[1:9]
        if _HEX8_RE.fullmatch(cand):
            return cand.lower()

    m = _HEX8_RE.search(v)
    if not m:
        return None
    return m.group(0).lower()


@dataclass
class TaskRefIndex:
    """In-memory index mapping receipt tokens to internal task IDs."""

    _token_to_task_id: dict[str, str] = field(default_factory=dict)

    def add(self, task_id: str, ref: str) -> None:
        token = normalize_task_ref(ref)
        if not token:
            return
        self._token_to_task_id[token] = task_id

    def resolve(self, ref_or_task_id: str) -> str | None:
        """Resolve either an internal task_id or a receipt string to task_id."""
        if not ref_or_task_id:
            return None

        # If it looks like a receipt, map it.
        token = normalize_task_ref(ref_or_task_id)
        if token and token in self._token_to_task_id:
            return self._token_to_task_id[token]

        # Fall back to treating it as a raw task_id.
        return ref_or_task_id

