"""
cortex/hippo/compaction/helpers.py — Pure helper functions.
"""

from __future__ import annotations

import hashlib
import re
import time
from datetime import datetime

from cortex.hippo.summarize import SummarizeResult

from .types import CompactionLevel


def estimate_tokens(text: str) -> int:
    """Rough token estimate: ~4 chars per token."""
    return max(1, -(-len(text) // 4))


def generate_summary_id(content: str) -> str:
    """Generate deterministic summary ID: 'sum_' + 16 hex chars."""
    digest = hashlib.sha256(
        (content + str(time.time_ns())).encode()
    ).hexdigest()
    return f"sum_{digest[:16]}"


def format_timestamp(dt_str: str, timezone: str = "UTC") -> str:
    """Format ISO datetime string for prompt display."""
    if not dt_str:
        return "unknown"
    # Just return the string truncated to minute precision for prompts
    try:
        # Handle ISO format: 2026-03-15T01:08:52Z
        dt = datetime.fromisoformat(dt_str.replace("Z", "+00:00"))
        return dt.strftime("%Y-%m-%d %H:%M UTC")
    except Exception:
        return dt_str[:16] if len(dt_str) >= 16 else dt_str


def _escalation_result(result: SummarizeResult, level: CompactionLevel) -> SummarizeResult:
    """Tag a SummarizeResult with the escalation level."""
    # The SummarizeResult already has quality info from the summarizer
    return SummarizeResult(
        content=result.content,
        quality_score=result.quality_score,
        quality_breakdown=result.quality_breakdown,
        source=result.source,
        mode_used=result.mode_used,
    )


def _extract_file_ids(text: str) -> list[str]:
    """Extract file_xxx references from text."""
    return list(set(re.findall(r"\bfile_[a-f0-9]{8,}\b", text)))
