import { readFileSync } from 'node:fs'

const args = process.argv.slice(2)
const promptArg = args[args.length - 1]
const prompt = promptArg?.startsWith('@') ? readFileSync(promptArg.slice(1), 'utf8') : promptArg

if (prompt.includes('fail')) {
  console.error('nope')
  process.exit(7)
}

if (prompt.includes('model-error')) {
  console.log(JSON.stringify({ type: 'session', id: 'pi-session-1' }))
  console.log(JSON.stringify({
    type: 'message_end',
    message: {
      role: 'assistant',
      content: [],
      stopReason: 'error',
      errorMessage: 'fake provider model error',
    },
  }))
  console.log(JSON.stringify({ type: 'agent_end', messages: [] }))
  process.exit(0)
}

const extensionIndex = args.indexOf('--extension')
const extensionPath = extensionIndex >= 0 ? args[extensionIndex + 1] : undefined
const extensionSource = extensionPath ? readFileSync(extensionPath, 'utf8') : ''
const structured = extensionSource.includes('smol_workflows_structured_output')
const output = structured
  ? JSON.stringify({ summary: 'structured pi summary', prompt, extensionRegisteredTool: extensionSource.includes('pi.registerTool(structuredOutputTool)') })
  : `fake pi: ${prompt}`
const usage = prompt.includes('cache-alias')
  ? {
      input_tokens: 5,
      output_tokens: 3,
      cache: { read: 4, write: 2 },
      cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
    }
  : {
      input: 13,
      output: 8,
      cacheRead: 2,
      cacheWrite: 3,
      totalTokens: 26,
      cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
    }

console.log(JSON.stringify({ type: 'session', id: 'pi-session-1' }))
if (structured) {
  const details = JSON.parse(output)
  console.log(JSON.stringify({ type: 'tool_execution_start', toolName: 'smol_workflows_structured_output', toolCallId: 'call-1', args: details }))
  if (prompt.includes('structured-tool-error-with-args')) {
    console.log(JSON.stringify({
      type: 'tool_execution_end',
      toolName: 'smol_workflows_structured_output',
      toolCallId: 'call-1',
      result: { content: [{ type: 'text', text: 'Tool validation failed.' }] },
      isError: true,
    }))
  } else {
    console.log(JSON.stringify({
      type: 'tool_execution_end',
      toolName: 'smol_workflows_structured_output',
      toolCallId: 'call-1',
      result: {
        content: [{ type: 'text', text: 'Structured output captured successfully.' }],
        details,
        terminate: true,
      },
      isError: false,
    }))
  }
} else if (prompt.includes('message-update-only')) {
  console.log(JSON.stringify({
    type: 'message_update',
    assistantMessageEvent: {
      type: 'text_end',
      content: output,
      partial: { role: 'assistant', content: [{ type: 'text', text: output }] },
    },
  }))
} else if (prompt.includes('agent-end-message-without-role')) {
  console.log(JSON.stringify({
    type: 'agent_end',
    messages: [
      { role: 'user', content: [{ type: 'text', text: prompt }] },
      { api: 'openai-responses', content: [{ type: 'thinking', thinking: '...' }, { type: 'text', text: output }] },
    ],
  }))
} else if (prompt.includes('tool-result-only')) {
  console.log(JSON.stringify({
    type: 'tool_execution_end',
    result: { content: [{ type: 'text', text: output }] },
  }))
  console.log(JSON.stringify({ type: 'agent_end', messages: [{ role: 'user', content: prompt }] }))
} else {
  console.log(JSON.stringify({ type: 'message_end', message: { role: 'assistant', content: [{ type: 'text', text: output }], usage } }))
  console.log(JSON.stringify({ type: 'agent_end', messages: [{ role: 'assistant', content: [{ type: 'text', text: output }], usage }] }))
}
