import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { getCalibration, getTwinState } from '@/lib/services/twin-service'

export const dynamic = 'force-dynamic'

/**
 * How much of this twin is measurement (§31, §84).
 *
 * Fidelity and calibration are returned together because they answer two halves of one
 * question: how well instrumented the twin is, and whether what it predicts has matched
 * what was subsequently recorded.
 */
export const GET = apiRoute<{ code: string }>({ permission: 'twin.read' }, async ({ params }) => {
  const [state, calibration] = await Promise.all([
    getTwinState(params.code),
    getCalibration(params.code),
  ])
  if (!state) throw new ApiError(ERROR_CODES.notFound)

  return {
    twin: state.twin,
    fidelity: state.fidelity,
    calibration: calibration
      ? {
          samples: calibration.samples,
          meanAbsPct: calibration.meanAbsPct,
          biasPct: calibration.biasPct,
          drift: calibration.drift,
          perChannel: calibration.perChannel,
          recommendation: calibration.recommendation,
          recommendationAr: calibration.recommendationAr,
        }
      : null,
  }
})
