from __future__ import annotations

import json
from pathlib import Path

_GEMINI_TOOL_NAME_MAP = {
    "read_file": "Read",
    "ReadFile": "Read",
    "write_file": "Write",
    "WriteFile": "Write",
    "edit": "Edit",
    "Edit": "Edit",
    "glob": "Glob",
    "FindFiles": "Glob",
    "grep": "Grep",
    "Grep": "Grep",
    "shell": "Bash",
    "Shell": "Bash",
    "write_todos": "TodoWrite",
    "WriteTodos": "TodoWrite",
}


def normalize_tool_name(tool_name: object) -> str | None:
    if not isinstance(tool_name, str) or not tool_name.strip():
        return None
    normalized = tool_name.strip()
    return _GEMINI_TOOL_NAME_MAP.get(normalized, normalized)


def summarize_tool_input(tool_input: object) -> str:
    if not isinstance(tool_input, dict):
        return ""
    parts: list[str] = []
    file_path = tool_input.get("file_path")
    if isinstance(file_path, str) and file_path.strip():
        parts.append(f"file_path={file_path.strip()}")
    pattern = tool_input.get("pattern")
    if isinstance(pattern, str) and pattern.strip():
        parts.append(f'pattern="{pattern.strip()}"')
    description = tool_input.get("description")
    if isinstance(description, str) and description.strip():
        parts.append(f'description="{description.strip()}"')
    command = tool_input.get("command")
    if isinstance(command, str) and command.strip():
        parts.append(f'command="{command.strip()}"')
    todos = tool_input.get("todos")
    if isinstance(todos, list):
        parts.append(f"todos={len(todos)}")
    return " ".join(parts)


def extract_tool_activity_from_transcript_path(transcript_path: str | Path | None) -> str | None:
    if isinstance(transcript_path, str):
        candidate = transcript_path.strip()
        if not candidate:
            return None
        path = Path(candidate)
    elif isinstance(transcript_path, Path):
        path = transcript_path
    else:
        return None

    if not path.exists():
        return None

    events: list[str] = []
    try:
        for raw_line in path.read_text(encoding="utf-8").splitlines():
            line = raw_line.strip()
            if not line:
                continue
            try:
                item = json.loads(line)
            except json.JSONDecodeError:
                continue
            if not isinstance(item, dict):
                continue
            item_type = item.get("type")
            if item_type == "tool_use":
                tool_name = normalize_tool_name(item.get("tool_name")) or "tool"
                summary = summarize_tool_input(item.get("parameters"))
                events.append(f"tool call: {tool_name}" + (f" {summary}" if summary else ""))
                continue
            if item_type == "tool_result":
                status = item.get("status")
                if isinstance(status, str) and status.strip():
                    events.append(f"tool result: {status.strip()}")
                else:
                    events.append("tool result received")
                continue
            if item_type == "result":
                status = item.get("status")
                stats = item.get("stats")
                parts: list[str] = []
                if isinstance(status, str) and status.strip():
                    parts.append(status.strip())
                if isinstance(stats, dict):
                    duration = stats.get("duration_ms")
                    if isinstance(duration, (int, float)):
                        parts.append(f"duration={duration}ms")
                    tool_calls = stats.get("tool_calls")
                    if isinstance(tool_calls, int):
                        parts.append(f"tool_calls={tool_calls}")
                if parts:
                    events.append("completed (" + ", ".join(parts) + ")")
    except OSError:
        return None

    if not events:
        return None
    return "\n".join(events[-6:])
