from __future__ import annotations

from datetime import datetime
from typing import Optional

from . import state


def log_turn_details(
    player_action: str,
    last_prompt: str,
    strategy_name: str,
    die_roll: int,
    model: str,
    temperature: float,
    max_tokens: int,
    book_log: str,
    log_entry: str,
    ambience: Optional[str],
    tool_calls: list,
    meta_log: str = "",
) -> None:
    """Write structured turn summary to llm.log and fire TUI debug event."""
    ts = datetime.now().isoformat()
    output_chars = len(book_log)
    output_words = len(book_log.split()) if book_log else 0

    state.append_llm_log("")
    state.append_llm_log(f"┌─ Turn Details — {ts}")
    state.append_llm_log(f"├─ Input: {player_action}")
    state.append_llm_log(f"├─ Last Prompt: {last_prompt}")
    state.append_llm_log(f"├─ Strategy: {strategy_name}")
    state.append_llm_log(f"├─ Dice: {die_roll} (1d6)")
    state.append_llm_log(f"├─ Model: {model} | Temp: {temperature} | Tokens: {max_tokens}")
    state.append_llm_log(f"├─ Output: {output_chars} chars ({output_words} words)")
    state.append_llm_log(f"├─ Log Entry: {log_entry}")
    state.append_llm_log(f"├─ Ambience: {ambience or 'None'}")
    state.append_llm_log(f"├─ Meta Log: {(meta_log or '')[:80]}")
    tools_preview = ", ".join(tc.get("tool", "?") for tc in tool_calls)
    state.append_llm_log(f"├─ Tool Calls: {len(tool_calls)} ({tools_preview})")
    state.append_llm_log(
        "└─────────────────────────────────────────────────────────────────────────────────────────┘"
    )
