"""Shared helper functions for CLI agent hook integrations."""
from __future__ import annotations

import json
import logging
import uuid
from datetime import datetime, timezone
from typing import Any

logger = logging.getLogger("staso")


def new_id() -> str:
    return str(uuid.uuid4())


def now_iso() -> str:
    return datetime.now(tz=timezone.utc).isoformat()


def ts_to_iso(unix_ts: float) -> str:
    return datetime.fromtimestamp(unix_ts, tz=timezone.utc).isoformat()


def parse_iso_to_epoch(iso_str: str) -> float | None:
    """Parse ISO 8601 timestamp to unix epoch seconds. Returns None on failure."""
    if not iso_str:
        return None
    try:
        return datetime.fromisoformat(iso_str).timestamp()
    except (ValueError, TypeError):
        return None


def safe_json(obj: Any) -> str:
    try:
        return json.dumps(obj, default=str)
    except (TypeError, ValueError):
        logger.warning("staso: failed to serialize object: %s", type(obj).__name__)
        return "{}"


def turn_span_name(prompt: str, turn_count: int) -> str:
    """Generate a human-readable turn span name from the user prompt."""
    if not prompt or not prompt.strip():
        return f"turn {turn_count}"
    truncated = prompt.strip().replace("\n", " ")
    if len(truncated) > 80:
        truncated = truncated[:77] + "..."
    return truncated
