/**
 * GET/PUT /api/sdk/agents/[agentId]/soul — SOUL-Datei lesen/schreiben
 *
 * GET: Content + Metadaten, ?history=true fuer Backup-Versionen
 * PUT: Backup erstellen -> neuen Content schreiben -> Cache invalidieren
 */

import { NextRequest, NextResponse } from 'next/server'
import { getAgentById } from '@/lib/sdk/agents/agent-registry'
import {
  readSoulFile,
  writeSoulFile,
  listSoulBackups,
  getSoulFileStats,
} from '@/lib/sdk/agents/soul-reader'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ agentId: string }> }
) {
  try {
    const { agentId } = await params
    const agent = getAgentById(agentId)

    if (!agent) {
      return NextResponse.json({ error: 'Agent not found' }, { status: 404 })
    }

    const showHistory = request.nextUrl.searchParams.get('history') === 'true'

    if (showHistory) {
      const backups = await listSoulBackups(agentId)
      return NextResponse.json({ agentId, backups })
    }

    const content = await readSoulFile(agentId)
    const fileStats = await getSoulFileStats(agentId)

    return NextResponse.json({
      agentId,
      content: content || '',
      updatedAt: fileStats?.updatedAt || null,
      size: fileStats?.size || 0,
    })
  } catch (error) {
    console.error('Error reading SOUL file:', error)
    return NextResponse.json({ error: 'Failed to read SOUL file' }, { status: 500 })
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ agentId: string }> }
) {
  try {
    const { agentId } = await params
    const agent = getAgentById(agentId)

    if (!agent) {
      return NextResponse.json({ error: 'Agent not found' }, { status: 404 })
    }

    const body = await request.json()
    const { content } = body

    if (typeof content !== 'string' || content.trim().length === 0) {
      return NextResponse.json({ error: 'Content is required' }, { status: 400 })
    }

    await writeSoulFile(agentId, content)

    const fileStats = await getSoulFileStats(agentId)

    return NextResponse.json({
      agentId,
      updatedAt: fileStats?.updatedAt || new Date().toISOString(),
      size: fileStats?.size || content.length,
      message: 'SOUL file updated successfully',
    })
  } catch (error) {
    console.error('Error writing SOUL file:', error)
    return NextResponse.json({ error: 'Failed to write SOUL file' }, { status: 500 })
  }
}
