import { NextRequest, NextResponse } from 'next/server'

/**
 * Agent Sessions API
 *
 * GET - List all active agent sessions
 * POST - Create/start a new session (for testing)
 */

interface AgentSession {
  id: string
  agentType: string
  agentId: string
  userId: string
  userName: string
  state: 'active' | 'paused' | 'completed' | 'failed'
  createdAt: string
  lastActivity: string
  checkpointCount: number
  messagesProcessed: number
  currentTask: string | null
  avgResponseTime: number
}

// Mock sessions data (in production, query from PostgreSQL/Redis)
function getMockSessions(): AgentSession[] {
  const now = new Date()
  return [
    {
      id: `session-${Date.now()}-001`,
      agentType: 'tutor-agent',
      agentId: 'tutor-1',
      userId: 'user-123',
      userName: 'Max Mustermann',
      state: 'active',
      createdAt: new Date(now.getTime() - 75 * 60000).toISOString(),
      lastActivity: new Date(now.getTime() - 37000).toISOString(),
      checkpointCount: 5,
      messagesProcessed: 23,
      currentTask: 'Erklaere Quadratische Funktionen',
      avgResponseTime: 245
    },
    {
      id: `session-${Date.now()}-002`,
      agentType: 'tutor-agent',
      agentId: 'tutor-2',
      userId: 'user-456',
      userName: 'Anna Schmidt',
      state: 'active',
      createdAt: new Date(now.getTime() - 45 * 60000).toISOString(),
      lastActivity: new Date(now.getTime() - 108000).toISOString(),
      checkpointCount: 3,
      messagesProcessed: 12,
      currentTask: 'Hilfe bei Gedichtanalyse',
      avgResponseTime: 312
    },
    {
      id: `session-${Date.now()}-003`,
      agentType: 'grader-agent',
      agentId: 'grader-1',
      userId: 'user-789',
      userName: 'Frau Mueller (Lehrerin)',
      state: 'active',
      createdAt: new Date(now.getTime() - 105 * 60000).toISOString(),
      lastActivity: new Date(now.getTime() - 180000).toISOString(),
      checkpointCount: 12,
      messagesProcessed: 45,
      currentTask: 'Korrektur Klausur 10b - Arbeit 7/24',
      avgResponseTime: 1205
    },
    {
      id: `session-${Date.now()}-004`,
      agentType: 'quality-judge',
      agentId: 'judge-1',
      userId: 'system',
      userName: 'System (BQAS)',
      state: 'active',
      createdAt: new Date(now.getTime() - 465 * 60000).toISOString(),
      lastActivity: new Date(now.getTime() - 1000).toISOString(),
      checkpointCount: 156,
      messagesProcessed: 892,
      currentTask: 'Quality Check Queue Processing',
      avgResponseTime: 89
    },
    {
      id: `session-${Date.now()}-005`,
      agentType: 'orchestrator',
      agentId: 'orchestrator-main',
      userId: 'system',
      userName: 'System',
      state: 'active',
      createdAt: new Date(now.getTime() - 945 * 60000).toISOString(),
      lastActivity: now.toISOString(),
      checkpointCount: 2341,
      messagesProcessed: 8934,
      currentTask: 'Routing incoming requests',
      avgResponseTime: 12
    },
    {
      id: `session-${Date.now()}-006`,
      agentType: 'tutor-agent',
      agentId: 'tutor-3',
      userId: 'user-101',
      userName: 'Tim Berger',
      state: 'paused',
      createdAt: new Date(now.getTime() - 150 * 60000).toISOString(),
      lastActivity: new Date(now.getTime() - 90 * 60000).toISOString(),
      checkpointCount: 8,
      messagesProcessed: 34,
      currentTask: null,
      avgResponseTime: 278
    },
    {
      id: `session-${Date.now()}-007`,
      agentType: 'grader-agent',
      agentId: 'grader-2',
      userId: 'user-202',
      userName: 'Herr Weber (Lehrer)',
      state: 'completed',
      createdAt: new Date(now.getTime() - 345 * 60000).toISOString(),
      lastActivity: new Date(now.getTime() - 225 * 60000).toISOString(),
      checkpointCount: 24,
      messagesProcessed: 120,
      currentTask: null,
      avgResponseTime: 1102
    },
    {
      id: `session-${Date.now()}-008`,
      agentType: 'alert-agent',
      agentId: 'alert-1',
      userId: 'system',
      userName: 'System (Monitoring)',
      state: 'active',
      createdAt: new Date(now.getTime() - 945 * 60000).toISOString(),
      lastActivity: new Date(now.getTime() - 2000).toISOString(),
      checkpointCount: 48,
      messagesProcessed: 256,
      currentTask: 'Monitoring System Health',
      avgResponseTime: 45
    }
  ]
}

// GET - List all sessions
export async function GET(request: NextRequest) {
  try {
    const url = new URL(request.url)
    const state = url.searchParams.get('state')
    const agentType = url.searchParams.get('agentType')
    const limit = parseInt(url.searchParams.get('limit') || '100')
    const offset = parseInt(url.searchParams.get('offset') || '0')

    let sessions = getMockSessions()

    // Apply filters
    if (state) {
      sessions = sessions.filter(s => s.state === state)
    }
    if (agentType) {
      sessions = sessions.filter(s => s.agentType === agentType)
    }

    // Calculate stats
    const stats = {
      total: sessions.length,
      active: sessions.filter(s => s.state === 'active').length,
      paused: sessions.filter(s => s.state === 'paused').length,
      completed: sessions.filter(s => s.state === 'completed').length,
      failed: sessions.filter(s => s.state === 'failed').length,
      totalMessages: sessions.reduce((sum, s) => sum + s.messagesProcessed, 0),
      avgResponseTime: Math.round(
        sessions.reduce((sum, s) => sum + s.avgResponseTime, 0) / sessions.length
      )
    }

    // Apply pagination
    const paginatedSessions = sessions.slice(offset, offset + limit)

    return NextResponse.json({
      sessions: paginatedSessions,
      stats,
      pagination: {
        total: sessions.length,
        limit,
        offset,
        hasMore: offset + limit < sessions.length
      },
      timestamp: new Date().toISOString()
    })
  } catch (error) {
    console.error('Error fetching sessions:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to fetch sessions' },
      { status: 500 }
    )
  }
}

// POST - Create new session (for testing)
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { agentType, userId, userName, context } = body

    if (!agentType || !userId) {
      return NextResponse.json(
        { error: 'agentType and userId are required' },
        { status: 400 }
      )
    }

    // In production, create session via agent-core SessionManager
    const newSession: AgentSession = {
      id: `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      agentType,
      agentId: `${agentType.replace('-agent', '')}-${Math.floor(Math.random() * 100)}`,
      userId,
      userName: userName || userId,
      state: 'active',
      createdAt: new Date().toISOString(),
      lastActivity: new Date().toISOString(),
      checkpointCount: 0,
      messagesProcessed: 0,
      currentTask: context?.task || null,
      avgResponseTime: 0
    }

    return NextResponse.json({
      success: true,
      session: newSession,
      message: 'Session created successfully'
    }, { status: 201 })
  } catch (error) {
    console.error('Error creating session:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to create session' },
      { status: 500 }
    )
  }
}
