import 'server-only'

import { createAdminClient } from '@/lib/supabase/admin'
import { PERMIT_COST_DISCLAIMER, permitFeesForAi, tripPermitFees } from '@/lib/domain/permit-cost'
import { logTripAiEvent, tripAiRequestId } from '@/lib/observability/trip-ai-log'

export interface HhaTripSyncResult {
  ok: boolean
  agentToken?: string
  matchedAllOrders?: boolean
  error?: string
}

function hhaBaseUrl() {
  return process.env.HHA_API_BASE_URL || process.env.FLASK_API_BASE_URL || ''
}

function hhaToken() {
  return (
    process.env.HHA_API_CLIENT_SECRET ||
    process.env.HHA_WORKSPACE_SYNC_TOKEN ||
    process.env.FLASK_API_KEY ||
    ''
  )
}

export function isHhaSyncConfigured() {
  return Boolean(hhaBaseUrl() && hhaToken())
}

export function workspaceAgentToken(trip: { id: string; source_order_number?: string | null }) {
  const source = String(trip.source_order_number || '').trim()
  return `workspace:${/^\d{8}$/.test(source) ? source : trip.id}`
}

/** Load the canonical server-side trip snapshot and upsert it into GPT all_trips. */
export async function syncTripToHha(
  tripId: string,
  requestId?: string,
): Promise<HhaTripSyncResult> {
  const correlationId = requestId || tripAiRequestId()
  const startedAt = Date.now()
  const base = hhaBaseUrl()
  const token = hhaToken()
  if (!base || !token) {
    await logTripAiEvent('trip_sync_not_configured', {
      request_id: correlationId,
      trip_id: tripId,
      status: 'error',
    })
    return { ok: false, error: 'HHA sync is not configured' }
  }

  await logTripAiEvent('trip_sync_started', {
    request_id: correlationId,
    trip_id: tripId,
  })

  const admin = createAdminClient()
  const [tripResult, unitResult, permitsResult, documentsResult, participantsResult, requestsResult] =
    await Promise.all([
      admin.from('trips').select('*').eq('id', tripId).single(),
      admin.from('trip_units').select('*').eq('trip_id', tripId).maybeSingle(),
      admin.from('permits').select('*').eq('trip_id', tripId),
      admin
        .from('documents')
        .select('id, trip_id, kind, file_name, mime_type, size_bytes, content_hash, storage_provider, storage_path, external_url, source_system, source_record_id, created_at')
        .eq('trip_id', tripId),
      admin
        .from('trip_participants')
        .select('id, name, email, phone, role, status')
        .eq('trip_id', tripId),
      admin
        .from('service_requests')
        .select('id, type, state_code, notes, status, vendor_order_id, created_at')
        .eq('trip_id', tripId),
    ])

  // A failed child query must never look like an empty permit list and erase
  // the mirrored routes. Retry the complete snapshot instead.
  const snapshotError = [tripResult, unitResult, permitsResult, documentsResult, participantsResult, requestsResult]
    .find((result) => result.error)?.error
  if (snapshotError || !tripResult.data) {
    await logTripAiEvent('trip_sync_snapshot_failed', {
      request_id: correlationId,
      trip_id: tripId,
      status: 'error',
      error_code: snapshotError?.code,
      duration_ms: Date.now() - startedAt,
    })
    return { ok: false, error: snapshotError?.message || 'Trip not found' }
  }

  const controller = new AbortController()
  const timer = setTimeout(() => controller.abort(), 30_000)
  try {
    const response = await fetch(`${base.replace(/\/$/, '')}/api/workspace/update-trip`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
        ...(process.env.HHA_API_CLIENT_ID
          ? { 'X-HHA-Client-ID': process.env.HHA_API_CLIENT_ID }
          : {}),
        'X-Trip-AI-Request-ID': correlationId,
      },
      body: JSON.stringify({
        trip: tripResult.data,
        unit: unitResult.data ?? null,
        permits: permitsResult.data ?? [],
        // State permit fees, already summed and carrying the wording the answer
        // must use (2026-09-24, §15). Only roles allowed to hear it ask with
        // permit_cost_visible: true.
        permit_fees: (() => {
          const fees = tripPermitFees((permitsResult.data ?? []) as Parameters<typeof tripPermitFees>[0])
          return { label: fees.label, total: fees.total, currency: fees.currency, counted: fees.counted, missing: fees.missing, complete: fees.complete, warning: fees.warning, disclaimer: PERMIT_COST_DISCLAIMER, summary: permitFeesForAi(fees) }
        })(),
        documents: documentsResult.data ?? [],
        participants: participantsResult.data ?? [],
        service_requests: requestsResult.data ?? [],
      }),
      signal: controller.signal,
    })
    const body = (await response.json().catch(() => ({}))) as Record<string, unknown>
    if (!response.ok) {
      await logTripAiEvent('trip_sync_backend_failed', {
        request_id: correlationId,
        trip_id: tripId,
        status: 'error',
        http_status: response.status,
        duration_ms: Date.now() - startedAt,
      })
      return { ok: false, error: String(body.error || `GPT responded ${response.status}`) }
    }
    await logTripAiEvent('trip_sync_completed', {
      request_id: correlationId,
      trip_id: tripId,
      matched_all_orders: body.matched_all_orders === true,
      permit_count: permitsResult.data?.length ?? 0,
      document_count: documentsResult.data?.length ?? 0,
      participant_count: participantsResult.data?.length ?? 0,
      duration_ms: Date.now() - startedAt,
    })
    return {
      ok: true,
      agentToken: String(body.agent_token || workspaceAgentToken(tripResult.data)),
      matchedAllOrders: body.matched_all_orders === true,
    }
  } catch (error) {
    await logTripAiEvent('trip_sync_request_failed', {
      request_id: correlationId,
      trip_id: tripId,
      status: 'error',
      error_type: error instanceof Error ? error.name : 'UnknownError',
      duration_ms: Date.now() - startedAt,
    })
    return { ok: false, error: error instanceof Error ? error.message : 'GPT is unreachable' }
  } finally {
    clearTimeout(timer)
  }
}
