import { jsonResponse, errorResponse } from '../utils/cors'
import { getTranscriptAnalysis, listSessions, getActiveSession, resetSessionOffset, getClaudeStats, getClaudeUsage } from '../services/transcript-engine'
import type { TranscriptAnalysis } from '../services/transcript-engine'

export function handleClaudeUsage(): Response {
  const usage = getClaudeUsage()
  if (!usage) return errorResponse('Usage data not available', 404)
  return jsonResponse(usage)
}

export function handleClaudeStats(): Response {
  const stats = getClaudeStats()
  if (!stats) return errorResponse('Stats not available', 404)
  return jsonResponse(stats)
}

export function handleTranscriptSessions(): Response {
  const sessions = listSessions()
  return jsonResponse(sessions)
}

export function handleTranscriptActive(req: Request, url: URL): Response {
  if (req.method !== 'GET') return errorResponse('Method not allowed', 405)

  const agent = url.searchParams.get('agent') || 'claude'
  const activeSession = getActiveSession(agent)

  const sessionId = activeSession?.sessionId
  const analysis = getTranscriptAnalysis(sessionId, activeSession?.transcriptPath)

  if (!analysis) return errorResponse('No active session found', 404)

  // Reset offset so future incrementals start from here
  resetSessionOffset(analysis.sessionId)

  return jsonResponse({
    ...analysis,
    messages: analysis.messages.filter(m => !m.isMeta)
  })
}

export function handleTranscript(req: Request, url: URL, sessionId: string): Response {
  if (req.method !== 'GET') return errorResponse('Method not allowed', 405)

  const resolvedId = sessionId === 'latest' ? undefined : sessionId
  const analysis = getTranscriptAnalysis(resolvedId)

  if (!analysis) {
    return errorResponse('Transcript not found', 404)
  }

  // Section filtering
  const section = url.searchParams.get('section')
  if (section) {
    return handleSection(analysis, section)
  }

  // Full response (exclude thinking by default)
  const includeThinking = url.searchParams.get('includeThinking') === 'true'
  if (!includeThinking) {
    return jsonResponse({
      ...analysis,
      messages: analysis.messages.filter(m => !m.isMeta)
    })
  }

  return jsonResponse({
    ...analysis,
    messages: analysis.messages.filter(m => !m.isMeta)
  })
}

function handleSection(analysis: TranscriptAnalysis, section: string): Response {
  switch (section) {
    case 'messages':
      return jsonResponse({
        sessionId: analysis.sessionId,
        messages: analysis.messages.filter(m => !m.isMeta)
      })
    case 'tokens':
      return jsonResponse({
        sessionId: analysis.sessionId,
        tokens: analysis.tokens
      })
    case 'tools':
      return jsonResponse({
        sessionId: analysis.sessionId,
        tools: analysis.tools
      })
    case 'stats':
      return jsonResponse({
        sessionId: analysis.sessionId,
        stats: analysis.stats,
        model: analysis.model,
        version: analysis.version,
        duration: analysis.duration,
        startTime: analysis.startTime,
        endTime: analysis.endTime,
        lastStopReason: analysis.lastStopReason
      })
    case 'files':
      return jsonResponse({
        sessionId: analysis.sessionId,
        filesModified: analysis.filesModified
      })
    case 'subagents':
      return jsonResponse({
        sessionId: analysis.sessionId,
        subagents: analysis.subagents
      })
    default:
      return errorResponse(`Unknown section: ${section}. Valid: messages, tokens, tools, stats, files, subagents`, 400)
  }
}
