export interface ParsedMessage {
  type:
    | "text"
    | "system"
    | "tool_call"
    | "tool_result"
    | "session_end"
    | "error";
  content: string;
  meta?: {
    toolName?: string;
    isError?: boolean;
    cost?: number;
    duration?: number;
  };
}

export function formatToolCall(toolUse: any): string {
  const { name, input } = toolUse;

  if (name === "Bash") {
    return `$ ${input.command}${input.description ? "\n# " + input.description : ""}`;
  }

  if (name === "Read") {
    return `Read: ${input.file_path}${input.offset ? ` (lines ${input.offset}-${input.offset + (input.limit || 10)})` : ""}`;
  }

  if (name === "Edit") {
    return `Edit: ${input.file_path}\n${input.old_string.substring(0, 100)}${input.old_string.length > 100 ? "..." : ""}\n-> ${input.new_string.substring(0, 100)}${input.new_string.length > 100 ? "..." : ""}`;
  }

  if (name === "Write") {
    return `Write: ${input.file_path} (${input.content.length} chars)`;
  }

  if (name === "Task") {
    return `${input.subagent_type}: ${input.description}\n${input.prompt?.substring(0, 200)}${input.prompt && input.prompt.length > 200 ? "..." : ""}`;
  }

  return `${name}: ${JSON.stringify(input, null, 2)}`;
}

export function getMessageStyling(type: ParsedMessage["type"]): string {
  switch (type) {
    case "system":
      return "mb-1";
    case "text":
      return "mb-1";
    case "tool_call":
      return "mb-2";
    case "tool_result":
      return "mb-2";
    case "error":
      return "mb-2";
    case "session_end":
      return "mb-2";
    default:
      return "mb-1";
  }
}

export function parseAgentOutput(raw: string): ParsedMessage[] {
  const lines = raw.split("\n").filter(Boolean);
  const parsedMessages: ParsedMessage[] = [];

  for (const line of lines) {
    try {
      const event = JSON.parse(line);

      // System initialization
      if (event.type === "system" && event.session_id) {
        parsedMessages.push({
          type: "system",
          content: `Session started: ${event.session_id}`,
        });
      }

      // Assistant messages with text and tool calls
      else if (
        event.type === "assistant" &&
        Array.isArray(event.message?.content)
      ) {
        for (const block of event.message.content) {
          if (block.type === "text" && block.text) {
            parsedMessages.push({
              type: "text",
              content: block.text,
            });
          } else if (block.type === "tool_use") {
            parsedMessages.push({
              type: "tool_call",
              content: formatToolCall(block),
              meta: { toolName: block.name },
            });
          }
        }
      }

      // User messages with tool results
      else if (
        event.type === "user" &&
        Array.isArray(event.message?.content)
      ) {
        for (const block of event.message.content) {
          if (block.type === "tool_result") {
            const rawContent = block.content;
            const output =
              typeof rawContent === "string"
                ? rawContent
                : Array.isArray(rawContent)
                  ? rawContent
                      .map((c: any) => c.text ?? JSON.stringify(c))
                      .join("\n")
                  : (event.tool_use_result?.stdout || "");
            const stderr = event.tool_use_result?.stderr;

            if (stderr) {
              parsedMessages.push({
                type: "error",
                content: stderr,
                meta: { isError: true },
              });
            } else if (output) {
              const displayOutput =
                output.length > 1000
                  ? output.substring(0, 1000) + "\n... (truncated)"
                  : output;
              parsedMessages.push({
                type: "tool_result",
                content: displayOutput,
              });
            }
          }
        }
      }

      // Legacy streaming format
      else if (event.type === "stream_event" && event.event?.delta?.text) {
        parsedMessages.push({
          type: "text",
          content: event.event.delta.text,
        });
      }

      // Session completion
      else if (event.type === "result") {
        parsedMessages.push({
          type: "session_end",
          content: event.is_error ? "Session failed" : "Session completed",
          meta: {
            isError: event.is_error,
            cost: event.total_cost_usd,
            duration: event.duration_ms,
          },
        });
      }
    } catch {
      // Not JSON, display as-is
      parsedMessages.push({
        type: "error",
        content: line,
        meta: { isError: true },
      });
    }
  }
  return parsedMessages;
}
