import { listen } from "@tauri-apps/api/event";
import { claudeStore } from "$lib/stores/claude";
import { characterState } from "$lib/stores/character";
import type { ConnectionStatus, PermissionPromptEvent } from "$lib/types/messages";
import type { CharacterState } from "$lib/types/states";

interface StateChangePayload {
  state: CharacterState;
  tool_name: string | null;
}

interface OutputPayload {
  line_type: string;
  content: string;
  tool_name: string | null;
}

export async function initializeTauriListeners() {
  await listen<string>("claude:connection", (event) => {
    const status = event.payload as ConnectionStatus;
    claudeStore.setConnectionStatus(status);

    if (status === "connected") {
      claudeStore.addLine("system", "Connected to Claude Code");
      characterState.setState("idle");
    } else if (status === "disconnected") {
      claudeStore.addLine("system", "Disconnected from Claude Code");
      characterState.setState("idle");
    } else if (status === "error") {
      claudeStore.addLine("error", "Connection error");
      characterState.setTemporaryState("error", 3000);
    }
  });

  await listen<StateChangePayload>("claude:state", (event) => {
    const { state } = event.payload;

    const stateMap: Record<string, CharacterState> = {
      idle: "idle",
      thinking: "thinking",
      typing: "typing",
      searching: "searching",
      coding: "coding",
      mcp: "mcp",
      permission: "permission",
      success: "success",
      error: "error",
    };

    const mappedState = stateMap[state.toLowerCase()] || "idle";

    if (mappedState === "success" || mappedState === "error") {
      characterState.setTemporaryState(mappedState, 3000);
    } else {
      characterState.setState(mappedState);
    }
  });

  await listen<OutputPayload>("claude:output", (event) => {
    const { line_type, content, tool_name } = event.payload;
    claudeStore.addLine(
      line_type as "user" | "assistant" | "system" | "tool" | "error",
      content,
      tool_name || undefined
    );
  });

  await listen<string>("claude:stream", () => {
    // no-op
  });

  await listen<string>("claude:session", (event) => {
    claudeStore.setSessionId(event.payload);
    claudeStore.addLine("system", `Session: ${event.payload.substring(0, 8)}...`);
  });

  await listen<string>("claude:cwd", (event) => {
    claudeStore.setWorkingDirectory(event.payload);
  });

  await listen<PermissionPromptEvent>("claude:permission", (event) => {
    const { id, tool_name, tool_input, description } = event.payload;
    claudeStore.requestPermission({
      id,
      tool: tool_name,
      description,
      input: tool_input,
    });
    claudeStore.addLine("system", `Permission requested for: ${tool_name}`);
  });

  console.log("Tauri event listeners initialized");
}
