import 'server-only'

import { extractRateConfirmation } from '@/lib/adapters/flask'
import { processWorkspacePermit } from '@/lib/data/permit-processing'
import { syncTripToHha } from '@/lib/integrations/hha-trip-sync'
import { logOperationEvent } from '@/lib/observability/operation-events'
import { logExtractionFailure } from '@/lib/observability/extraction-error-log'

/**
 * What happens AFTER a new trip has opened (Nash, 2026-10-01: "create the
 * trip immediately and open it and let it process in background. We should
 * not have this user wait so long on step two").
 *
 * Reading a permit takes 12–25 seconds and a trip often carries several, so
 * the Create Trip action no longer waits for any of it. It stores the files,
 * creates the permit rows and redirects; this runs once the response is sent
 * (`after()` in the action).
 *
 * Nothing here is the only copy of the work. Every permit row already has a
 * durable job in `permit_processing_jobs` (database trigger, migration 0041),
 * so a server restart in the middle is recovered by the scheduled worker
 * (`/api/internal/permit-processing`, every minute) — the lease on a job that
 * was being read simply expires and it is claimed again.
 *
 * Never throws: a failure is logged and left to the retry queue.
 */
export interface NewTripBackgroundWork {
  tripId: string
  origin: string
  /** The rate con is read again WITH the trip attached, so the agent backend files it under this trip. */
  rateCon?: { file: Blob; fileName: string; documentId: string; sourceUrl: string } | null
  /** In-memory files save a download; the queue re-downloads from storage if this run is lost. */
  permits: Array<{ permitId: string; file?: Blob }>
  /** How many permits are read at the same time. */
  concurrency?: number
}

export interface NewTripBackgroundResult {
  synced: boolean
  rateConRead: boolean | null
  permits: Array<{ permitId: string; ok: boolean; status: string }>
}

export const NEW_TRIP_PERMIT_CONCURRENCY = 3

export async function processNewTripInBackground(work: NewTripBackgroundWork): Promise<NewTripBackgroundResult> {
  const result: NewTripBackgroundResult = { synced: false, rateConRead: work.rateCon ? false : null, permits: [] }
  const started = Date.now()
  try {
    const sync = await syncTripToHha(work.tripId)
    result.synced = sync.ok
    if (!sync.ok) console.error('New trip sync failed:', sync.error)
  } catch (error) {
    console.error('New trip sync failed:', error instanceof Error ? error.message : error)
  }

  // The rate con and the permits are independent reads; run them side by side.
  const rateConTask = (async () => {
    if (!work.rateCon) return
    try {
      const r = await extractRateConfirmation(work.rateCon.file, work.rateCon.fileName, {
        tripId: work.tripId, documentId: work.rateCon.documentId, sourceUrl: work.rateCon.sourceUrl,
      })
      result.rateConRead = r.ok
    } catch (error) {
      await logExtractionFailure({ kind: 'ratecon', stage: 'workspace_processing',
        tripId: work.tripId, documentId: work.rateCon.documentId,
        internalCode: error instanceof Error && /^[a-z_]{3,80}$/.test(error.message)
          ? error.message : 'ratecon_background_exception' })
    }
  })()

  const queue = [...work.permits]
  const worker = async () => {
    for (let next = queue.shift(); next; next = queue.shift()) {
      try {
        const r = await processWorkspacePermit({ permitId: next.permitId, file: next.file, origin: work.origin })
        result.permits.push({ permitId: next.permitId, ok: r.ok, status: r.status })
      } catch (error) {
        // processWorkspacePermit reports its own failures; this is the unexpected kind. The queue retries.
        console.error('Background permit processing failed:', { permit_id: next.permitId, error: error instanceof Error ? error.message : 'unknown' })
        result.permits.push({ permitId: next.permitId, ok: false, status: 'pending' })
      }
    }
  }
  const lanes = Math.max(1, Math.min(work.concurrency ?? NEW_TRIP_PERMIT_CONCURRENCY, work.permits.length))
  await Promise.all([rateConTask, ...Array.from({ length: lanes }, worker)])

  await logOperationEvent({
    area: 'permit', event: 'new_trip_background', outcome: result.permits.every((p) => p.ok) ? 'success' : 'failed', tripId: work.tripId,
    detail: {
      permits: work.permits.length, permits_ok: result.permits.filter((p) => p.ok).length,
      rate_con_read: result.rateConRead, synced: result.synced, seconds: Math.round((Date.now() - started) / 1000),
    },
  })
  return result
}
