"""Reasoning Audit Trail — stores and queries response traces."""

from __future__ import annotations

import uuid
from datetime import datetime, timezone
from typing import Dict, List, Optional

from .store import MemoryStore


def store_trace(
    store: MemoryStore,
    query: str,
    node_ids_used: List[str],
    response: str = "",
    scope: str = "global",
    metadata: Optional[Dict] = None,
) -> str:
    """Record a reasoning trace and return its ID."""
    trace_id = uuid.uuid4().hex
    store.save_trace(
        trace_id=trace_id,
        timestamp=datetime.now(timezone.utc),
        query=query,
        node_ids_used=node_ids_used,
        response=response,
        scope=scope,
        metadata=metadata,
    )
    return trace_id


def get_trace(store: MemoryStore, trace_id: str) -> Optional[Dict]:
    """Retrieve a single trace by ID."""
    return store.get_trace(trace_id)


def list_traces(
    store: MemoryStore,
    scope: Optional[str] = None,
    limit: int = 50,
) -> List[Dict]:
    """List recent traces, optionally filtered by scope."""
    return store.list_traces(scope=scope, limit=limit)


def traces_using_node(store: MemoryStore, node_id: str) -> List[Dict]:
    """Find all traces that used a specific memory node."""
    return store.traces_using_node(node_id)


def explain_trace(store: MemoryStore, trace_id: str) -> Optional[str]:
    """Return a human-readable explanation of how a response was formed.

    Shows the query, the memories that were used, and the response.
    """
    trace = store.get_trace(trace_id)
    if trace is None:
        return None

    lines = [
        f"Trace {trace['id'][:8]} — {trace['timestamp'].strftime('%Y-%m-%d %H:%M:%S UTC')}",
        f"Query: {trace['query']}",
        f"Scope: {trace['scope']}",
        "",
        "Memories used:",
    ]

    for nid in trace["node_ids_used"]:
        node = store.get_node(nid)
        if node:
            lines.append(f"  [{nid[:8]}] {node.content[:100]}")
        else:
            lines.append(f"  [{nid[:8]}] (deleted)")

    if trace["response"]:
        lines.append("")
        lines.append(f"Response: {trace['response'][:500]}")

    if trace["metadata"]:
        lines.append("")
        lines.append(f"Metadata: {trace['metadata']}")

    return "\n".join(lines)
