import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { toPerturbation } from '@/lib/api/overlay'
import { scenarioParamsSchema } from '@/lib/api/schemas'
import { analyseAsset } from '@/lib/services/intelligence-service'

export const dynamic = 'force-dynamic'

/**
 * The belief around a prediction, rather than a single number (§14, §15, §16).
 *
 * Returns the window, the four confidences and the component breakdown behind
 * "why this confidence?", plus whatever degraded it.
 */
export const GET = apiRoute({ permission: 'predictions.read' }, async ({ searchParams }) => {
  const assetCode = searchParams.get('asset')
  if (!assetCode) throw new ApiError(ERROR_CODES.validationFailed, { details: { asset: 'required' } })

  const overlayRaw = searchParams.get('overlay')
  const overlay = overlayRaw ? scenarioParamsSchema.safeParse(JSON.parse(overlayRaw)) : null
  if (overlay && !overlay.success) {
    throw new ApiError(ERROR_CODES.validationFailed, { details: { overlay: 'invalid' } })
  }

  const intel = await analyseAsset(assetCode, {
    perturbation: overlay?.success ? toPerturbation(overlay.data) : undefined,
  })
  if (!intel) throw new ApiError(ERROR_CODES.notFound)

  return {
    assetCode,
    ts: intel.ts,
    uncertainty: intel.uncertainty,
    envelope: intel.envelope,
    physics: {
      verdict: intel.physics.verdict,
      confidence: intel.physics.confidence,
      summary: intel.physics.summary,
      summaryAr: intel.physics.summaryAr,
      checks: intel.physics.checks,
    },
  }
})
