import { useCopilotStore } from "@/stores/copilot.store";
import type { ToolCall } from "@/stores/copilot.store";

/**
 * Composable providing mock Wails binding wrappers for the AI copilot.
 *
 * All functions simulate Claude-style behavior until real Wails bindings
 * (AIService.*) are connected.
 */
export function useCopilot() {
  const store = useCopilotStore();

  /** Simulate word-by-word streaming output. */
  async function mockStream(
    text: string,
    onDelta: (word: string) => void,
  ): Promise<void> {
    const words = text.split(" ");
    for (const word of words) {
      await new Promise((r) => setTimeout(r, 30 + Math.random() * 70));
      onDelta(word + " ");
    }
  }

  /** Simulate a tool call execution with realistic delay. */
  async function mockToolCall(
    name: string,
    _input: Record<string, unknown>,
  ): Promise<unknown> {
    await new Promise((r) => setTimeout(r, 500 + Math.random() * 1000));

    if (name === "list_sessions") return [];
    if (name === "terminal_read") {
      return {
        lines: [
          "$ systemctl status nginx",
          "● nginx.service - A high performance web server",
          "   Loaded: loaded (/lib/systemd/system/nginx.service; enabled)",
          "   Active: active (running) since Mon 2026-03-17 08:30:12 UTC",
          "   Main PID: 1234 (nginx)",
          "   Tasks: 5 (limit: 4915)",
          "   Memory: 12.4M",
        ],
      };
    }
    if (name === "terminal_write") return { status: "ok" };
    if (name === "rdp_screenshot") {
      return { thumbnail: "data:image/jpeg;base64,/9j/4AAQ..." };
    }
    if (name === "rdp_click") return { status: "ok" };
    if (name === "rdp_type") return { status: "ok" };
    if (name === "sftp_read") return { content: "# example file content" };
    if (name === "sftp_write") return { bytesWritten: 1024 };

    return { status: "ok" };
  }

  /**
   * Process a user message — route to the appropriate mock response.
   *
   * Routes:
   * - "hello"/"hey" -> greeting
   * - "ssh"/"server"/"check" -> terminal tool calls
   * - "rdp"/"desktop"/"screen" -> RDP screenshot tool call
   * - default -> list_sessions assessment
   */
  async function processMessage(text: string): Promise<void> {
    const lower = text.toLowerCase();

    store.isStreaming = true;
    const assistantMsg = store.createAssistantMessage();

    try {
      if (/\b(hello|hey|hi)\b/.test(lower)) {
        await mockStream(
          "XO online. I have access to your active sessions. What's the mission, Commander?",
          (word) => store.appendStreamDelta(word),
        );
      } else if (/\b(ssh|server|check|nginx|status)\b/.test(lower)) {
        await mockStream(
          "On it. Let me check the server status.",
          (word) => store.appendStreamDelta(word),
        );

        // Tool call 1: terminal_write
        const writeCallId = `tc-${Date.now()}-1`;
        const writeCall: ToolCall = {
          id: writeCallId,
          name: "terminal_write",
          input: { sessionId: "s1", text: "systemctl status nginx" },
          status: "pending",
        };
        store.addToolCall(writeCall);

        const writeResult = await mockToolCall("terminal_write", writeCall.input);
        store.completeToolCall(writeCallId, writeResult);

        // Tool call 2: terminal_read
        const readCallId = `tc-${Date.now()}-2`;
        const readCall: ToolCall = {
          id: readCallId,
          name: "terminal_read",
          input: { sessionId: "s1", lines: 20 },
          status: "pending",
        };
        store.addToolCall(readCall);

        const readResult = await mockToolCall("terminal_read", readCall.input);
        store.completeToolCall(readCallId, readResult);

        // Summary
        store.appendStreamDelta("\n\n");
        await mockStream(
          "Nginx is **active and running**. The service has been up since 08:30 UTC today, using 12.4M of memory with 5 active tasks. Everything looks healthy.",
          (word) => store.appendStreamDelta(word),
        );
      } else if (/\b(rdp|desktop|screen|screenshot)\b/.test(lower)) {
        await mockStream(
          "Taking a screenshot of the remote desktop.",
          (word) => store.appendStreamDelta(word),
        );

        // Tool call: rdp_screenshot
        const callId = `tc-${Date.now()}`;
        const call: ToolCall = {
          id: callId,
          name: "rdp_screenshot",
          input: { sessionId: "s2" },
          status: "pending",
        };
        store.addToolCall(call);

        const result = await mockToolCall("rdp_screenshot", call.input);
        store.completeToolCall(callId, result);

        store.appendStreamDelta("\n\n");
        await mockStream(
          "I can see the Windows desktop. The screen shows the default wallpaper with a few application shortcuts. No error dialogs or unusual activity detected.",
          (word) => store.appendStreamDelta(word),
        );
      } else {
        await mockStream(
          "Understood. Let me assess the situation.",
          (word) => store.appendStreamDelta(word),
        );

        // Tool call: list_sessions
        const callId = `tc-${Date.now()}`;
        const call: ToolCall = {
          id: callId,
          name: "list_sessions",
          input: {},
          status: "pending",
        };
        store.addToolCall(call);

        const result = await mockToolCall("list_sessions", call.input);
        store.completeToolCall(callId, result);

        store.appendStreamDelta("\n\n");
        await mockStream(
          "I've reviewed your current sessions. No active connections detected at the moment. Would you like me to connect to a specific server or run a diagnostic?",
          (word) => store.appendStreamDelta(word),
        );
      }

      // Track mock output tokens
      store.tokenUsage.output += Math.ceil(
        (assistantMsg.content.length) / 4,
      );
    } finally {
      store.isStreaming = false;
    }
  }

  return { mockStream, mockToolCall, processMessage };
}
