import { jsonResponse, errorResponse } from '../utils/cors'
import { PORT_TERMINAL } from '../config'

type ClaudeStatus =
  | 'idle'
  | 'thinking'             // UserPromptSubmit / PostToolUse - Claude is thinking
  | 'toolUse'              // PreToolUse - Using a tool (generic)
  | 'reading'              // PreToolUse(Read/Glob/Grep) - Reading files
  | 'writing'              // PreToolUse(Edit/Write) - Writing files
  | 'sessionStart'         // SessionStart - Session just started
  | 'sessionEnd'           // SessionEnd - Session ended
  | 'permissionRequest'    // PermissionRequest - Waiting for user permission
  | 'interrupted'          // PostToolUseFailure with is_interrupt
  | 'error'                // PostToolUseFailure without is_interrupt

interface ClaudeStatusPayload {
  status: ClaudeStatus
  tool?: string
  agent?: string
}

export async function handleClaudeStatus(req: Request): Promise<Response | null> {
  if (req.method !== 'POST') return null

  try {
    const body = await req.json() as ClaudeStatusPayload

    const validStatuses: ClaudeStatus[] = [
      'idle', 'thinking', 'toolUse', 'reading', 'writing',
      'sessionStart', 'sessionEnd', 'permissionRequest',
      'interrupted', 'error'
    ]
    if (!body.status || !validStatuses.includes(body.status)) {
      return errorResponse(`Invalid status. Must be one of: ${validStatuses.join(', ')}`, 400)
    }

    // Forward to terminal server for WebSocket broadcast
    try {
      await fetch(`http://localhost:${PORT_TERMINAL}/claude-status`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
      })
    } catch (e) {
      console.error('[claude-status] Failed to forward to terminal server:', e)
    }

    return jsonResponse({ success: true, status: body.status })
  } catch (e) {
    return errorResponse('Invalid JSON body', 400)
  }
}
