import { STATE_NAMES } from '@/lib/domain/states'
import { canSeePermitCost, redactCostsForPilot } from '@/lib/domain/permit-cost'

export interface SourceFinding {
  source: string
  label: string
  state: string
  stateCode: string | null
  status: string
  indicated: string
  score: number | null
}
export interface SourceCitation extends SourceFinding {
  id: string
  snippet: string
  permitIds: string[]
}
export interface AgentEvidence {
  version: 1
  confidenceScore: number | null
  confidenceReason: string
  findings: SourceFinding[]
  citations: SourceCitation[]
  truncated?: boolean
}

const LABELS: Record<string, string> = { provision: 'State Provision', state_notes: 'Internal State Notes', permit: 'Permit Document', conclusion: 'Conclusion', order_database: 'Trip records', state_review: 'State review' }
export const record = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}
const text = (value: unknown, limit = 2000) => typeof value === 'string' ? value.trim().slice(0, limit) : ''
const list = (value: unknown) => Array.isArray(value) ? value.slice(0, 32) : []
const score = (value: unknown): number | null => {
  if ((typeof value !== 'number' && typeof value !== 'string') || String(value).trim() === '') return null
  const n = Number(value)
  return Number.isFinite(n) && n >= 0 && n <= 100 ? n : null
}
export const isUuid = (value: string) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)

function finding(value: unknown): SourceFinding | null {
  const row = record(value)
  const source = text(row.source, 40)
  if (!Object.hasOwn(LABELS, source)) return null
  const state = text(row.state || (source === 'state_review' ? row.label : ''), 80)
  const givenCode = text(row.stateCode || row.state_code, 80).toUpperCase()
  const stateCode = /^[A-Z]{2}$/.test(givenCode) ? givenCode : Object.entries(STATE_NAMES).find(([code, name]) => code === state.toUpperCase() || name.toLowerCase() === state.toLowerCase())?.[0] ?? null
  return { source, label: LABELS[source], state, stateCode, status: text(row.status, 40), indicated: text(row.indicated), score: score(row.score) }
}

/** Keep only bounded, public source findings. Raw tools, arguments and URLs never enter chat. */
export function normalizeAgentEvidence(value: unknown): AgentEvidence | null {
  const raw = record(value)
  const stored = raw.version === 1
  let findings = list(stored ? raw.findings : raw.reasoning_trace).map(finding).filter((item): item is SourceFinding => !!item)
  const citations = list(stored ? raw.citations : raw.source_citations).flatMap((value, index) => {
    const row = record(value)
    const base = finding(row)
    if (!base) return []
    const permitIds = list(stored ? row.permitIds : row.workspace_permit_ids).filter((id): id is string => typeof id === 'string' && isUuid(id))
    return [{ ...base, id: text(row.id, 120) || `source-${index}`, snippet: text(row.snippet, 4000), permitIds: [...new Set(permitIds)] }]
  })
  if (!findings.length) {
    // Older tools may provide source status without a comparison trace.
    const summary = record(raw.source_summary)
    findings = Object.entries(summary).flatMap(([source, detail]) => {
      const found = finding({ ...record(detail), source })
      return found ? [found] : []
    })
  }
  const confidenceScore = score(stored ? raw.confidenceScore : raw.confidence)
  const confidenceReason = text(stored ? raw.confidenceReason : raw.confidence_reason)
  if (!findings.length && !citations.length && confidenceScore == null && !confidenceReason) return null
  const evidence: AgentEvidence = { version: 1, confidenceScore, confidenceReason, findings, citations }
  if (raw.truncated === true || (Array.isArray(raw.reasoning_trace) && raw.reasoning_trace.length > 32) || (Array.isArray(raw.source_citations) && raw.source_citations.length > 32)) evidence.truncated = true
  // Limit UTF-8 bytes too: multibyte excerpts must fit the database bound.
  while (new TextEncoder().encode(JSON.stringify(evidence)).length > 120000 && (citations.length || findings.length)) {
    evidence.truncated = true
    if (citations.length) citations.pop()
    else findings.pop()
  }
  return evidence
}

export function evidenceForRole(value: unknown, role: string | null | undefined): AgentEvidence | null {
  const evidence = normalizeAgentEvidence(value)
  if (!evidence || canSeePermitCost(role)) return evidence
  const redact = (value: string) => agentTextForRole(value, role)
  return normalizeAgentEvidence({ ...evidence, confidenceReason: redact(evidence.confidenceReason),
    findings: evidence.findings.map(item => ({ ...item, state: redact(item.state), indicated: redact(item.indicated) })),
    citations: evidence.citations.map(item => ({ ...item, id: redact(item.id), state: redact(item.state), indicated: redact(item.indicated), snippet: redact(item.snippet) })) })
}

export function agentTextForRole(value: string, role: string | null | undefined): string {
  return canSeePermitCost(role) ? value : redactCostsForPilot(value)
    .replace(/\b(?:USD|CAD|EUR|GBP)\s*\d[\d,]*(?:\.\d{1,2})?|\b\d[\d,]*(?:\.\d{1,2})?\s*(?:USD|CAD|EUR|GBP)\b|[€£]\s*\d[\d,]*(?:\.\d{1,2})?/gi, '[amount hidden]')
    .replace(/((?:price|permit_fee|service_fee|permit_cost_amount|fee_amount|estimated_os_price|estimated_ow_price)["']?\s*[:=]\s*["']?)\d[\d,]*(?:\.\d+)?/gi, '$1[amount hidden]')
    .replace(/(\b(?:fees?|prices?|costs?)\s+(?:(?:is|of)\s+)?)(\d[\d,]*(?:\.\d+)?)/gi, '$1[amount hidden]')
}
