/**
 * Shared RPC schema for PTY bridge between Bun process and WebView.
 *
 * Bun holds the Unix socket connection to agor-ptyd; the WebView calls
 * into Bun via requests, and Bun pushes output/close events via messages.
 */

// ── Requests (WebView → Bun, expects a response) ─────────────────────────────

export type PtyRPCRequests = {
  /** Create a PTY session and subscribe to its output. */
  "pty.create": {
    params: {
      sessionId: string;
      cols: number;
      rows: number;
      /** Working directory for the shell process. */
      cwd?: string;
    };
    response: { ok: boolean; error?: string };
  };
  /** Write raw input bytes (base64-encoded) to a PTY session. */
  "pty.write": {
    params: {
      sessionId: string;
      /** UTF-8 text typed by the user (xterm onData delivers this). */
      data: string;
    };
    response: { ok: boolean };
  };
  /** Notify the daemon that the terminal dimensions changed. */
  "pty.resize": {
    params: { sessionId: string; cols: number; rows: number };
    response: { ok: boolean };
  };
  /** Unsubscribe from a session's output (session stays alive). */
  "pty.unsubscribe": {
    params: { sessionId: string };
    response: { ok: boolean };
  };
  /** Kill a PTY session. */
  "pty.close": {
    params: { sessionId: string };
    response: { ok: boolean };
  };

  // ── Settings RPC ───────────────────────────────────────────────────────────

  /** Get a single setting value by key. Returns null if not set. */
  "settings.get": {
    params: { key: string };
    response: { value: string | null };
  };
  /** Persist a setting key/value pair. */
  "settings.set": {
    params: { key: string; value: string };
    response: { ok: boolean };
  };
  /** Return all settings as a flat object. */
  "settings.getAll": {
    params: Record<string, never>;
    response: { settings: Record<string, string> };
  };
  /** Return all persisted projects. */
  "settings.getProjects": {
    params: Record<string, never>;
    response: { projects: Array<{ id: string; config: string }> };
  };
  /** Persist a project config (JSON-serialised on the caller side). */
  "settings.setProject": {
    params: { id: string; config: string };
    response: { ok: boolean };
  };

  // ── Custom Themes RPC ──────────────────────────────────────────────────────

  /** Return all user-saved custom themes. */
  "themes.getCustom": {
    params: Record<string, never>;
    response: { themes: Array<{ id: string; name: string; palette: Record<string, string> }> };
  };
  /** Save (upsert) a custom theme by id. */
  "themes.saveCustom": {
    params: { id: string; name: string; palette: Record<string, string> };
    response: { ok: boolean };
  };
  /** Delete a custom theme by id. */
  "themes.deleteCustom": {
    params: { id: string };
    response: { ok: boolean };
  };

  // ── File I/O RPC ──────────────────────────────────────────────────────────

  /** List directory children (files + subdirs). Returns sorted entries. */
  "files.list": {
    params: { path: string };
    response: {
      entries: Array<{
        name: string;
        type: "file" | "dir";
        size: number;
      }>;
      error?: string;
    };
  };
  /** Read a file's content. Returns text for text files, base64 for binary. */
  "files.read": {
    params: { path: string };
    response: {
      content?: string;
      encoding: "utf8" | "base64";
      size: number;
      error?: string;
    };
  };
  /** Write text content to a file. */
  "files.write": {
    params: { path: string; content: string };
    response: { ok: boolean; error?: string };
  };

  // ── Groups RPC ─────────────────────────────────────────────────────────────

  /** Return all project groups. */
  "groups.list": {
    params: Record<string, never>;
    response: { groups: Array<{ id: string; name: string; icon: string; position: number }> };
  };

  // ── Project clone RPC ──────────────────────────────────────────────────────

  /** Clone a project into a git worktree. branchName must match /^[a-zA-Z0-9\/_.-]+$/. */
  "project.clone": {
    params: { projectId: string; branchName: string };
    response: { ok: boolean; project?: { id: string; config: string }; error?: string };
  };

  // ── Window control RPC ─────────────────────────────────────────────────────

  /** Minimize the main window. */
  "window.minimize": {
    params: Record<string, never>;
    response: { ok: boolean };
  };
  /** Toggle maximize/restore on the main window. */
  "window.maximize": {
    params: Record<string, never>;
    response: { ok: boolean };
  };
  /** Close the main window. */
  "window.close": {
    params: Record<string, never>;
    response: { ok: boolean };
  };
  /** Get current window frame (x, y, width, height). */
  "window.getFrame": {
    params: Record<string, never>;
    response: { x: number; y: number; width: number; height: number };
  };

  // ── Keybindings RPC ────────────────────────────────────────────────────────

  /** Return all persisted custom keybindings (overrides only). */
  "keybindings.getAll": {
    params: Record<string, never>;
    response: { keybindings: Record<string, string> };
  };
  /** Persist a single keybinding override. */
  "keybindings.set": {
    params: { id: string; chord: string };
    response: { ok: boolean };
  };
  /** Reset a keybinding to default (removes override). */
  "keybindings.reset": {
    params: { id: string };
    response: { ok: boolean };
  };

  // ── Agent RPC ─────────────────────────────────────────────────────────────

  /** Start an agent session with a given provider. */
  "agent.start": {
    params: {
      sessionId: string;
      provider: "claude" | "codex" | "ollama";
      prompt: string;
      cwd?: string;
      model?: string;
      systemPrompt?: string;
      maxTurns?: number;
      permissionMode?: string;
      claudeConfigDir?: string;
      extraEnv?: Record<string, string>;
    };
    response: { ok: boolean; error?: string };
  };
  /** Stop a running agent session. */
  "agent.stop": {
    params: { sessionId: string };
    response: { ok: boolean; error?: string };
  };
  /** Send a follow-up prompt to a running agent session. */
  "agent.prompt": {
    params: { sessionId: string; prompt: string };
    response: { ok: boolean; error?: string };
  };
  /** List all active agent sessions with their state. */
  "agent.list": {
    params: Record<string, never>;
    response: {
      sessions: Array<{
        sessionId: string;
        provider: string;
        status: string;
        costUsd: number;
        inputTokens: number;
        outputTokens: number;
        startedAt: number;
      }>;
    };
  };

  // ── Session persistence RPC ────────────────────────────────────────────

  /** Save/update a session record. */
  "session.save": {
    params: {
      projectId: string; sessionId: string; provider: string;
      status: string; costUsd: number; inputTokens: number;
      outputTokens: number; model: string; error?: string;
      createdAt: number; updatedAt: number;
    };
    response: { ok: boolean };
  };
  /** Load the most recent session for a project. */
  "session.load": {
    params: { projectId: string };
    response: {
      session: {
        projectId: string; sessionId: string; provider: string;
        status: string; costUsd: number; inputTokens: number;
        outputTokens: number; model: string; error?: string;
        createdAt: number; updatedAt: number;
      } | null;
    };
  };
  /** List sessions for a project (max 20). */
  "session.list": {
    params: { projectId: string };
    response: {
      sessions: Array<{
        projectId: string; sessionId: string; provider: string;
        status: string; costUsd: number; inputTokens: number;
        outputTokens: number; model: string; error?: string;
        createdAt: number; updatedAt: number;
      }>;
    };
  };
  /** Save agent messages (batch). */
  "session.messages.save": {
    params: {
      messages: Array<{
        sessionId: string; msgId: string; role: string; content: string;
        toolName?: string; toolInput?: string; timestamp: number;
        costUsd?: number; inputTokens?: number; outputTokens?: number;
      }>;
    };
    response: { ok: boolean };
  };
  /** Load all messages for a session. */
  "session.messages.load": {
    params: { sessionId: string };
    response: {
      messages: Array<{
        sessionId: string; msgId: string; role: string; content: string;
        toolName?: string; toolInput?: string; timestamp: number;
        costUsd: number; inputTokens: number; outputTokens: number;
      }>;
    };
  };

  // ── btmsg RPC ──────────────────────────────────────────────────────────

  /** Register an agent in btmsg. */
  "btmsg.registerAgent": {
    params: {
      id: string; name: string; role: string;
      groupId: string; tier: number; model?: string;
    };
    response: { ok: boolean };
  };
  /** List agents for a group. */
  "btmsg.getAgents": {
    params: { groupId: string };
    response: {
      agents: Array<{
        id: string; name: string; role: string; groupId: string;
        tier: number; model: string | null; status: string; unreadCount: number;
      }>;
    };
  };
  /** Send a direct message between agents. */
  "btmsg.sendMessage": {
    params: { fromAgent: string; toAgent: string; content: string };
    response: { ok: boolean; messageId?: string; error?: string };
  };
  /** Get message history between two agents. */
  "btmsg.listMessages": {
    params: { agentId: string; otherId: string; limit?: number };
    response: {
      messages: Array<{
        id: string; fromAgent: string; toAgent: string; content: string;
        read: boolean; replyTo: string | null; createdAt: string;
        senderName: string | null; senderRole: string | null;
      }>;
    };
  };
  /** Mark messages as read. */
  "btmsg.markRead": {
    params: { agentId: string; messageIds: string[] };
    response: { ok: boolean };
  };
  /** List channels for a group. */
  "btmsg.listChannels": {
    params: { groupId: string };
    response: {
      channels: Array<{
        id: string; name: string; groupId: string; createdBy: string;
        memberCount: number; createdAt: string;
      }>;
    };
  };
  /** Create a channel. */
  "btmsg.createChannel": {
    params: { name: string; groupId: string; createdBy: string };
    response: { ok: boolean; channelId?: string };
  };
  /** Get channel messages. */
  "btmsg.getChannelMessages": {
    params: { channelId: string; limit?: number };
    response: {
      messages: Array<{
        id: string; channelId: string; fromAgent: string; content: string;
        createdAt: string; senderName: string; senderRole: string;
      }>;
    };
  };
  /** Send a channel message. */
  "btmsg.sendChannelMessage": {
    params: { channelId: string; fromAgent: string; content: string };
    response: { ok: boolean; messageId?: string };
  };
  /** Record agent heartbeat. */
  "btmsg.heartbeat": {
    params: { agentId: string };
    response: { ok: boolean };
  };
  /** Get dead letter queue entries. */
  "btmsg.getDeadLetters": {
    params: { limit?: number };
    response: {
      letters: Array<{
        id: number; fromAgent: string; toAgent: string;
        content: string; error: string; createdAt: string;
      }>;
    };
  };
  /** Log an audit event. */
  "btmsg.logAudit": {
    params: { agentId: string; eventType: string; detail: string };
    response: { ok: boolean };
  };
  /** Get audit log. */
  "btmsg.getAuditLog": {
    params: { limit?: number };
    response: {
      entries: Array<{
        id: number; agentId: string; eventType: string;
        detail: string; createdAt: string;
      }>;
    };
  };

  // ── bttask RPC ─────────────────────────────────────────────────────────

  /** List tasks for a group. */
  "bttask.listTasks": {
    params: { groupId: string };
    response: {
      tasks: Array<{
        id: string; title: string; description: string; status: string;
        priority: string; assignedTo: string | null; createdBy: string;
        groupId: string; parentTaskId: string | null; sortOrder: number;
        createdAt: string; updatedAt: string; version: number;
      }>;
    };
  };
  /** Create a task. */
  "bttask.createTask": {
    params: {
      title: string; description: string; priority: string;
      groupId: string; createdBy: string; assignedTo?: string;
    };
    response: { ok: boolean; taskId?: string; error?: string };
  };
  /** Update task status with optimistic locking. */
  "bttask.updateTaskStatus": {
    params: { taskId: string; status: string; expectedVersion: number };
    response: { ok: boolean; newVersion?: number; error?: string };
  };
  /** Delete a task. */
  "bttask.deleteTask": {
    params: { taskId: string };
    response: { ok: boolean };
  };
  /** Add a comment to a task. */
  "bttask.addComment": {
    params: { taskId: string; agentId: string; content: string };
    response: { ok: boolean; commentId?: string };
  };
  /** List comments for a task. */
  "bttask.listComments": {
    params: { taskId: string };
    response: {
      comments: Array<{
        id: string; taskId: string; agentId: string;
        content: string; createdAt: string;
      }>;
    };
  };
  /** Count tasks in 'review' status. */
  "bttask.reviewQueueCount": {
    params: { groupId: string };
    response: { count: number };
  };

  // ── Search RPC ──────────────────────────────────────────────────────────

  /** Full-text search across messages, tasks, and btmsg. */
  "search.query": {
    params: { query: string; limit?: number };
    response: {
      results: Array<{
        resultType: string;
        id: string;
        title: string;
        snippet: string;
        score: number;
      }>;
    };
  };
  /** Index a message for search. */
  "search.indexMessage": {
    params: { sessionId: string; role: string; content: string };
    response: { ok: boolean };
  };
  /** Rebuild the entire search index. */
  "search.rebuild": {
    params: Record<string, never>;
    response: { ok: boolean };
  };

  // ── Plugin RPC ──────────────────────────────────────────────────────────

  /** Discover plugins from ~/.config/agor/plugins/. */
  "plugin.discover": {
    params: Record<string, never>;
    response: {
      plugins: Array<{
        id: string;
        name: string;
        version: string;
        description: string;
        main: string;
        permissions: string[];
      }>;
    };
  };
  /** Read a plugin file (path-traversal-safe). */
  "plugin.readFile": {
    params: { pluginId: string; filePath: string };
    response: { ok: boolean; content: string; error?: string };
  };
};

// ── Messages (Bun → WebView, fire-and-forget) ────────────────────────────────

export type PtyRPCMessages = {
  /** PTY output chunk. data is base64-encoded raw bytes from the daemon. */
  "pty.output": { sessionId: string; data: string };
  /** PTY session exited. */
  "pty.closed": { sessionId: string; exitCode: number | null };

  // ── Agent events (Bun → WebView) ─────────────────────────────────────────

  /** Agent message(s) parsed from sidecar NDJSON. */
  "agent.message": {
    sessionId: string;
    messages: Array<{
      id: string;
      type: string;
      parentId?: string;
      content: unknown;
      timestamp: number;
    }>;
  };
  /** Agent session status change. */
  "agent.status": {
    sessionId: string;
    status: string;
    error?: string;
  };
  /** Agent cost/token update. */
  "agent.cost": {
    sessionId: string;
    costUsd: number;
    inputTokens: number;
    outputTokens: number;
  };
};

// ── Combined schema ───────────────────────────────────────────────────────────

export type PtyRPCSchema = {
  requests: PtyRPCRequests;
  messages: PtyRPCMessages;
};
