/**
 * Demo Agent for the pilot driver replica (2026-09-12).
 *
 * Nash: "the pilot driver will use the agent to talk mostly… the same ability
 * to choose the whole trip or a specific state and only the states that are
 * shared with him he can ask questions about… voice first… change the
 * languages and all the same tools as the carrier driver has."
 *
 * The real ChatPanel is reused in `offline` mode; this module supplies the
 * minimal Trip/ChatMessage shapes it needs plus a local answerer that stays
 * inside the pilot's access scope (article §44). Sample knowledge comes from
 * the same state-info text the state-notes dialog shows.
 */

import type { ChatMessage, Trip } from '@/types/db'
import { getStateInfo } from '@/lib/demo/state-info'
import { stateName } from '@/lib/domain/states'
import { CHAT_LANGUAGES } from '@/lib/domain/languages'
import type { DemoPilotAssignment } from '@/lib/demo/pilot'

/** A Trip-shaped object so the shared ChatPanel can render an assignment. */
export function demoTripFor(a: DemoPilotAssignment): Trip {
  return {
    id: a.id,
    ref_code: a.ref,
    created_by: null,
    broker_page_id: null,
    status: a.status === 'completed' ? 'completed' : 'active',
    permit_source: 'upload',
    carrier_name: a.carrier,
    unit_number: a.truckInfo?.unitNumber ?? null,
    origin: a.origin,
    destination: a.destination,
    commodity: a.commodity,
    load_length_in: null,
    load_width_in: null,
    load_height_in: null,
    load_weight_lbs: null,
    overall_length_in: null,
    overall_width_in: null,
    overall_height_in: null,
    overall_weight_lbs: null,
    permit_policy: 'upload_allowed',
    payment_responsible_party: null,
    pickup_date: null,
    delivery_date: null,
    notes: null,
    completed_at: a.completedAt ?? null,
    created_at: `${a.createdAt}T09:00:00.000Z`,
    updated_at: `${a.createdAt}T09:00:00.000Z`,
  } as Trip
}

/** Shared permits only — the state selector is built from these. */
export function demoChatPermits(a: DemoPilotAssignment) {
  return a.permits.filter((p) => p.shared).map((p) => ({ id: p.id, state_code: p.state, permit_number: p.permitNumber }))
}

const HIDDEN = /rate con|rate confirmation|price|pricing|billing|margin|how much (is|are|do) (the|they) pay|invoice from the carrier|what.*paid/i

/** Scope-aware local answer. */
export function demoPilotAnswer(a: DemoPilotAssignment) {
  const sharedStates = [...new Set(a.permits.filter((p) => p.shared).map((p) => p.state))]
  const full = a.scopes.some((s) => s.type === 'full_trip')
  const langLabel = (code: string) => CHAT_LANGUAGES.find((l) => l.code === code)?.label ?? code

  return (question: string, stateCode: string | null, language: string): string => {
    const prefix = language && language !== 'en' ? `[${langLabel(language)}] ` : ''
    if (HIDDEN.test(question)) {
      return `${prefix}That document is not available for your role. Pilot access covers permits, routes, escort and curfew details for the states shared with you.`
    }
    // A state named in the question that is not shared with this pilot.
    const asked = a.permits.find((p) => !p.shared && (new RegExp(`\\b${p.state}\\b`, 'i').test(question) || new RegExp(stateName(p.state) || '$^', 'i').test(question)))
    if (asked && !full) {
      return `${prefix}${stateName(asked.state) || asked.state} has not been shared with you on this trip. Your access covers ${sharedStates.map((s) => stateName(s) || s).join(', ') || 'no states yet'} — ask the carrier dispatcher if you need it.`
    }
    if (sharedStates.length === 0) {
      return `${prefix}Nothing has been shared with you on this assignment yet, so there is no permit to answer from. The carrier can share states, permits or the full trip at any time.`
    }
    const code = stateCode || sharedStates[0]
    const permits = a.permits.filter((p) => p.shared && p.state === code)
    const info = getStateInfo(code)
    const q = question.toLowerCase()
    if (/escort|pilot|high pole|chase|lead/.test(q)) {
      return `${prefix}${stateName(code) || code}: ${permits.map((p) => `${p.permitNumber} — ${p.escort}`).join('; ')}. ${info['Escort info']}`
    }
    if (/curfew|night|hour|when can|move now|right now|weekend|holiday/.test(q)) {
      return `${prefix}${stateName(code) || code}: ${permits.map((p) => `${p.permitNumber} — curfew: ${p.curfew}`).join('; ')}. ${info['Travel info']}`
    }
    if (/valid|expire|effective|date/.test(q)) {
      return `${prefix}${permits.map((p) => `${p.permitNumber} is valid ${p.effective} → ${p.expires}`).join('; ')}.`
    }
    if (/sign|flag|light|beacon/.test(q)) return `${prefix}${info['Signs & more']}`
    if (/limit|legal|width|height|weight|length/.test(q)) return `${prefix}${info['Permit limits']} ${info['Legal limits']}`
    return `${prefix}For ${stateName(code) || code} you hold ${permits.length} shared permit(s): ${permits.map((p) => p.permitNumber).join(', ')}. Escort: ${permits[0]?.escort}. Curfew: ${permits[0]?.curfew}. Ask about escorts, curfews, validity, signs or limits for detail.`
  }
}

/** Starter conversation for the replica, in ChatMessage shape. */
export function demoPilotChat(a: DemoPilotAssignment, myUserId: string, myName: string): ChatMessage[] {
  const shared = a.permits.filter((p) => p.shared)
  if (shared.length === 0) return []
  const p = shared[0]
  const at = (m: number) => new Date(Date.now() - m * 60_000).toISOString()
  const base = { trip_id: a.id, permit_id: null, confidence: null, sources: null, feedback: null, is_private: false, private_for_user_id: null, answer_to_message_id: null }
  return [
    { ...base, id: 'demo-q1', user_id: myUserId, author_label: myName, author_role: 'pilot', is_ai: false, content: `Do I need a high pole for the ${stateName(p.state) || p.state} permit?`, state_code: p.state, created_at: at(12) },
    { ...base, id: 'demo-a1', user_id: null, author_label: 'Agent', author_role: 'agent', is_ai: true, content: `${p.permitNumber}: ${p.escort}.`, state_code: p.state, created_at: at(11) },
    { ...base, id: 'demo-q2', user_id: myUserId, author_label: myName, author_role: 'pilot', is_ai: false, content: 'Can you show me the rate confirmation for this load?', state_code: null, created_at: at(5) },
    { ...base, id: 'demo-a2', user_id: null, author_label: 'Agent', author_role: 'agent', is_ai: true, content: 'That document is not available for your role. Pilot access covers permits, routes, escort and curfew details for the states shared with you.', state_code: null, created_at: at(4) },
  ] as ChatMessage[]
}
