export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { promises as fs } from 'node:fs'
import path from 'node:path'

const SETTINGS_PATH = '/data/settings.json'
const DEFAULTS = {
  voiceProvider: 'anthropic',
  anthropicModel: 'claude-haiku-4-5-20251001',
  groqModel: 'meta-llama/llama-4-scout-17b-16e-instruct',
}

async function readSettings() {
  try {
    const raw = await fs.readFile(SETTINGS_PATH, 'utf-8')
    return { ...DEFAULTS, ...JSON.parse(raw) }
  } catch {
    return { ...DEFAULTS }
  }
}

export async function GET() {
  return NextResponse.json(await readSettings())
}

export async function POST(req: NextRequest) {
  const body = await req.json()
  const current = await readSettings()
  const updated = { ...current, ...body }
  await fs.mkdir(path.dirname(SETTINGS_PATH), { recursive: true })
  await fs.writeFile(SETTINGS_PATH, JSON.stringify(updated, null, 2), 'utf-8')
  return NextResponse.json(updated)
}
