import { AiPartPrice, AiPricing, normalizePartPrice, normalizePricing, } from "./ai-pricing"; export interface AiPart { price?: AiPartPrice; name: string; severity: string | null; confidence: number | null; side: string | null; carSide: string | null; bbox: { x1: number; y1: number; x2: number; y2: number } | null; damageTypes?: string[]; descriptions?: string[]; localized?: boolean; evidence?: AiEvidence[]; } export interface AiEvidence { imageIndex: number; filename: string | null; view: string | null; severity: string | null; linkStatus: string | null; instanceId: number | null; confidence: number | null; bbox: AiPart["bbox"]; polygon: [number, number][] | null; } export interface AiResult { pricing?: AiPricing; parts: AiPart[]; report: string; caseReport: string; requestId?: string | null; pipeline?: Record; vehicle?: { color: string | null; bodyType: string | null }; internalDamages?: Array<{ category: string | null; labelFa: string | null; likelihood: string | null; reason: string | null; }>; } const text = (v: unknown): string | null => typeof v === "string" ? v.trim().slice(0, 20000) : null; export class AiAssessmentError extends Error { constructor( public readonly code: string | null, public readonly requestId: string | null, public readonly httpStatus?: number, message = "AI assessment provider returned an error", ) { super(message); } } function boundingBox(value: any): AiPart["bbox"] { return value && [value.x1, value.y1, value.x2, value.y2].every( (n) => typeof n === "number" && Number.isFinite(n), ) && value.x2 > value.x1 && value.y2 > value.y1 ? { x1: value.x1, y1: value.y1, x2: value.x2, y2: value.y2 } : null; } const confidence = (value: unknown): number | null => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1 ? value : null; function strings(value: unknown): string[] { return Array.isArray(value) ? value .slice(0, 100) .map(text) .filter((item): item is string => !!item) : []; } /** Each durable job uploads exactly one image, whose evidence index is zero. */ function normalizeAssessment(raw: any): AiResult { if (!Array.isArray(raw.damaged_parts) || typeof raw.case_report !== "string") throw new Error("Invalid AI assessment response"); if ( raw.damaged_parts.length > 500 || (raw.internal_damages != null && !Array.isArray(raw.internal_damages)) || (raw.internal_damages?.length ?? 0) > 500 ) throw new Error("Invalid AI assessment collections"); let evidenceCount = 0; const parts = raw.damaged_parts.map((part: any): AiPart => { const name = text(part?.part); if (!name || (part.evidence != null && !Array.isArray(part.evidence))) throw new Error("Invalid AI damaged part"); evidenceCount += part.evidence?.length ?? 0; if (evidenceCount > 2000) throw new Error("Too many AI evidence records"); const evidence: AiEvidence[] = (part.evidence ?? []) .filter((item: any) => item?.image_index === 0) .map((item: any): AiEvidence => { const linked = part.localized === true && item.link_status === "linked"; const rawPolygon = item.part?.polygon; const polygon = linked && Array.isArray(rawPolygon) && rawPolygon.length >= 3 && rawPolygon.length <= 10000 && rawPolygon.every( (point: unknown) => Array.isArray(point) && point.length === 2 && point.every((n) => typeof n === "number" && Number.isFinite(n)), ) ? rawPolygon.map( (point: number[]) => [point[0], point[1]] as [number, number], ) : null; return { imageIndex: 0, filename: text(item.filename), view: text(item.view), severity: text(item.severity), linkStatus: text(item.link_status), instanceId: Number.isInteger(item.part?.instance_id) ? item.part.instance_id : null, confidence: confidence(item.part?.confidence), bbox: linked ? boundingBox(item.part?.box) : null, polygon, }; }); const firstBox = evidence.find((item) => item.bbox); return { name, price: normalizePartPrice(part.price), severity: text(part.severity), confidence: firstBox?.confidence ?? null, side: text(part.side), carSide: firstBox?.view ?? null, bbox: firstBox?.bbox ?? null, damageTypes: strings(part.damage_types), descriptions: strings(part.descriptions), localized: part.localized === true, evidence, }; }); return { parts, report: "", caseReport: text(raw.case_report) ?? "", requestId: text(raw.request_id), pricing: normalizePricing(raw.pricing), pipeline: Object.fromEntries( [ "version", "vlm_model", "price_model", "prompt_version", "part_model_sha256", "car_model_sha256", ].map((key) => [key, text(raw.pipeline?.[key])]), ), vehicle: { color: text(raw.vehicle?.color), bodyType: text(raw.vehicle?.body_type), }, internalDamages: (raw.internal_damages ?? []).map((item: any) => ({ category: text(item?.category), labelFa: text(item?.label_fa), likelihood: text(item?.likelihood), reason: text(item?.reason), })), }; } /** Preserve detections independently: repeated names may describe different boxes. */ export function normalizeAiResult(value: unknown): AiResult { const raw = value as any; if (raw?.error) throw new AiAssessmentError( text(raw.error.code), text(raw.error.request_id), undefined, text(raw.error.message) ?? undefined, ); if (raw && "damaged_parts" in raw) return normalizeAssessment(raw); const report = raw?.distinct_damaged_parts_report; if ( !report || !Array.isArray(report.parts) || typeof report.report !== "string" || typeof raw.case_report !== "string" ) { throw new Error("Invalid AI response"); } if (report.parts.length > 500) throw new Error("Too many AI detections"); const parts = report.parts.map((part: any): AiPart => { const name = text(part?.part_name); if (!name) throw new Error("Invalid AI part"); const b = part.part_bbox; const bbox = b && [b.x1, b.y1, b.x2, b.y2].every( (v) => typeof v === "number" && Number.isFinite(v), ) && b.x2 > b.x1 && b.y2 > b.y1 ? { x1: b.x1, y1: b.y1, x2: b.x2, y2: b.y2 } : null; return { name, bbox, severity: text(part.damage_severity), confidence: typeof part.confidence === "number" && Number.isFinite(part.confidence) && part.confidence >= 0 && part.confidence <= 1 ? part.confidence : null, side: text(part.side), carSide: text(part.car_side), }; }); return { parts, report: text(report.report) ?? "", caseReport: text(raw.case_report) ?? "", }; }