
import type { ExamTemplateDetail, ExamTemplateSource, TemplateReplacePayload } from '../../types/exam.types'

export const PAGE_HEIGHT = 1100
export const PAGE_WIDTH = 780
export const PAGE_GAP = 0

export interface CanvasPageGeometry { pageNumber: number; x: number; y: number; w: number; h: number }

export type ExamCanvasRegionKind = 'response' | 'context' | 'question_number' | 'mark_area' | 'reference' | 'furniture'
export type ExamCanvasShapeKind = 'boundary' | 'part' | ExamCanvasRegionKind

export interface CanvasBounds extends Record<string, number> { x: number; y: number; w: number; h: number }

export interface ExamCanvasShapeModel {
  /** Stable domain UUID persisted to Supabase. Do not reuse tldraw shape ids for new shapes. */
  id: string
  kind: ExamCanvasShapeKind
  x: number
  y: number
  w: number
  h: number
  label?: string
  maxMarks?: number
  answerType?: 'written' | 'mcq' | 'short' | 'diagram'
  responseForm?: 'lines' | 'answer-box' | 'working' | 'diagram' | 'tick-boxes' | 'table' | 'blanks'
  contextType?: string
  questionId?: string | null
  source?: ExamTemplateSource
  confirmed?: boolean
  confidence?: number | null
  derivation?: string | null
  reviewFlags?: string[]
}

export function pageForY(y: number, pages?: CanvasPageGeometry[]): number {
  if (pages?.length) {
    const hit = pages.find((page) => y >= page.y && y <= page.y + page.h)
    if (hit) return hit.pageNumber
    const nearest = pages.reduce((best, page) => {
      const dy = Math.min(Math.abs(y - page.y), Math.abs(y - (page.y + page.h)))
      return dy < best.dy ? { page, dy } : best
    }, { page: pages[0], dy: Number.POSITIVE_INFINITY })
    return nearest.page.pageNumber
  }
  return Math.max(1, Math.floor(y / PAGE_HEIGHT) + 1)
}

export function pageTop(page: number, pages?: CanvasPageGeometry[]): number {
  const hit = pages?.find((p) => p.pageNumber === page)
  return hit?.y ?? ((page - 1) * (PAGE_HEIGHT + PAGE_GAP))
}

function pageForShape(shape: Pick<ExamCanvasShapeModel, 'y' | 'h'>, pages?: CanvasPageGeometry[]): number {
  return pageForY(shape.y + shape.h / 2, pages)
}

export function isUuid(value: string | null | undefined): value is string {
  return typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
}

export function newDomainId(): string {
  if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
    return crypto.randomUUID()
  }
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = Math.floor(Math.random() * 16)
    const v = c === 'x' ? r : (r % 4) + 8
    return v.toString(16)
  })
}

function bounds(shape: Pick<ExamCanvasShapeModel, 'x' | 'y' | 'w' | 'h'>): CanvasBounds & Record<string, number> {
  return { x: shape.x, y: shape.y, w: shape.w, h: shape.h }
}

function pageGeometry(pageNumber: number, pages?: CanvasPageGeometry[]): CanvasPageGeometry {
  return pages?.find((page) => page.pageNumber === pageNumber) ?? { pageNumber, x: 0, y: pageTop(pageNumber, pages), w: PAGE_WIDTH, h: PAGE_HEIGHT }
}

function boundaryBounds(shape: Pick<ExamCanvasShapeModel, 'y' | 'h'>, pages?: CanvasPageGeometry[]): CanvasBounds & Record<string, number> {
  const page = pageGeometry(pageForShape(shape, pages), pages)
  return { x: page.x, y: shape.y, w: page.w, h: 8 }
}

function persistedSource(shape: ExamCanvasShapeModel): ExamTemplateSource {
  return shape.source ?? 'manual'
}

function persistedConfirmed(shape: ExamCanvasShapeModel): boolean {
  return shape.confirmed ?? persistedSource(shape) !== 'ai'
}

function persistedConfidence(shape: ExamCanvasShapeModel): number | null {
  return typeof shape.confidence === 'number' ? shape.confidence : null
}

function persistedDerivation(shape: ExamCanvasShapeModel): string | null {
  return shape.derivation ?? null
}

function contains(outer: CanvasBounds, inner: CanvasBounds): boolean {
  const ox2 = outer.x + outer.w
  const oy2 = outer.y + outer.h
  const ix2 = inner.x + inner.w
  const iy2 = inner.y + inner.h
  return inner.x >= outer.x && inner.y >= outer.y && ix2 <= ox2 && iy2 <= oy2
}

function bandContains(top: ExamCanvasShapeModel, bottom: ExamCanvasShapeModel, shape: ExamCanvasShapeModel): boolean {
  const minY = Math.min(top.y, bottom.y)
  const maxY = Math.max(top.y, bottom.y)
  const cy = shape.y + shape.h / 2
  return cy >= minY && cy <= maxY
}

export function serializeCanvasShapes(template: ExamTemplateDetail, shapes: ExamCanvasShapeModel[], pages?: CanvasPageGeometry[]): TemplateReplacePayload {
  const orderedBoundaries = shapes
    .filter((s) => s.kind === 'boundary')
    .sort((a, b) => (pageForShape(a, pages) - pageForShape(b, pages)) || (a.y - b.y))
  const parts = shapes.filter((s) => s.kind === 'part')
  const regions = shapes.filter((s) => s.kind !== 'boundary' && s.kind !== 'part')

  const questions: TemplateReplacePayload['questions'] = []
  const boundaries: TemplateReplacePayload['boundaries'] = []
  const bands: Array<{ questionId: string; top: ExamCanvasShapeModel; bottom: ExamCanvasShapeModel }> = []

  for (let i = 0; i < orderedBoundaries.length; i += 2) {
    const top = orderedBoundaries[i]
    const bottom = orderedBoundaries[i + 1]
    if (!top || !bottom) break
    const qNum = bands.length + 1
    const questionId = isUuid(top.questionId) ? top.questionId : isUuid(bottom.questionId) ? bottom.questionId : newDomainId()
    const label = top.label?.replace(/\s+(start|end)$/i, '') || bottom.label?.replace(/\s+(start|end)$/i, '') || `Q${qNum}`
    questions.push({ id: questionId, label, order: qNum - 1, max_marks: 0, is_container: true, mark_scheme: {}, source: persistedSource(top), confirmed: persistedConfirmed(top), confidence: persistedConfidence(top), derivation: persistedDerivation(top) })
    bands.push({ questionId, top, bottom })
    for (const b of [top, bottom]) {
      boundaries.push({ id: isUuid(b.id) ? b.id : newDomainId(), question_id: questionId, label: b === top ? `${label} start` : `${label} end`, page_index: pageForShape(b, pages) - 1, y: b.y, bounds: boundaryBounds(b, pages), source: persistedSource(b), confirmed: persistedConfirmed(b), confidence: persistedConfidence(b), derivation: persistedDerivation(b) })
    }
  }

  const partQuestionIds = new Map<string, string>()
  parts.sort((a, b) => (a.y - b.y) || (a.x - b.x)).forEach((part, index) => {
    const parentBand = bands.find((band) => bandContains(band.top, band.bottom, part))
    const qid = isUuid(part.questionId) ? part.questionId : isUuid(part.id) ? part.id : newDomainId()
    partQuestionIds.set(part.id, qid)
    questions.push({ id: qid, parent_id: parentBand?.questionId ?? null, label: part.label || `Part ${index + 1}`, order: index, max_marks: Number(part.maxMarks ?? 0), answer_type: part.answerType ?? 'written', mcq_options: null, mark_scheme: {}, is_container: false, spec_ref: null, bounds: bounds(part), page: pageForShape(part, pages), source: persistedSource(part), confirmed: persistedConfirmed(part), confidence: persistedConfidence(part), derivation: persistedDerivation(part) })
  })

  const response_areas: TemplateReplacePayload['response_areas'] = []
  for (const region of regions) {
    const containingPart = parts.find((part) => contains(bounds(part), bounds(region)))
    const fallbackPart = parts.find((part) => pageForShape(part, pages) === pageForShape(region, pages)) ?? parts[0]
    const questionId = containingPart ? partQuestionIds.get(containingPart.id) : fallbackPart ? partQuestionIds.get(fallbackPart.id) : undefined
    if (!questionId) continue
    const kind = region.kind as ExamCanvasRegionKind
    response_areas.push({ id: isUuid(region.id) ? region.id : newDomainId(), question_id: questionId, page: pageForShape(region, pages), bounds: bounds(region), kind, response_form: kind === 'response' ? (region.responseForm ?? 'lines') : null, context_type: kind === 'context' ? (region.contextType ?? 'generic') : null, source: persistedSource(region), confirmed: persistedConfirmed(region), confidence: persistedConfidence(region), mark_subtype: null, derivation: persistedDerivation(region) })
  }

  return { meta: { title: template.title, subject: template.subject ?? undefined, page_count: template.page_count ?? undefined, status: template.status }, questions, response_areas, boundaries, layout: template.layout ?? [] }
}

export function shapesFromTemplate(detail: ExamTemplateDetail, pages?: CanvasPageGeometry[]): ExamCanvasShapeModel[] {
  const shapes: ExamCanvasShapeModel[] = []
  const questions = new Map(detail.questions.map((q) => [q.id, q]))
  for (const b of detail.boundaries ?? []) {
    const page = pageGeometry((b.page_index ?? 0) + 1, pages)
    // Boundary rows are y-lines. The old bounds rect is vestigial: keep y/domain ids,
    // but render and save a full rendered-page-width horizontal rule.
    shapes.push({ id: b.id, kind: 'boundary', x: page.x, y: Number(b.y), w: page.w, h: 8, label: b.label ?? undefined, questionId: b.question_id, source: b.source, confirmed: b.confirmed, confidence: b.confidence, derivation: b.derivation })
  }
  for (const q of detail.questions ?? []) {
    if (q.is_container || !q.bounds) continue
    shapes.push({ id: q.id, kind: 'part', x: Number(q.bounds.x ?? 80), y: Number(q.bounds.y ?? 120), w: Number(q.bounds.w ?? 420), h: Number(q.bounds.h ?? 180), label: q.label, maxMarks: q.max_marks, answerType: (q.answer_type as ExamCanvasShapeModel['answerType']) ?? 'written', questionId: q.id, source: q.source, confirmed: q.confirmed, confidence: q.confidence, derivation: q.derivation })
  }
  for (const r of detail.response_areas ?? []) {
    const bb = r.bounds ?? { x: 100, y: pageTop(r.page, pages) + 360, w: 360, h: 120 }
    const q = questions.get(r.question_id)
    shapes.push({ id: r.id, kind: r.kind, x: Number(bb.x ?? 100), y: Number(bb.y ?? pageTop(r.page, pages) + 360), w: Number(bb.w ?? 360), h: Number(bb.h ?? 120), label: q ? `→ ${q.label}` : r.kind, responseForm: (r.response_form as ExamCanvasShapeModel['responseForm']) ?? undefined, contextType: r.context_type ?? undefined, questionId: r.question_id, source: r.source, confirmed: r.confirmed, confidence: r.confidence, derivation: r.derivation })
  }
  return addCheapReviewFlags(shapes, pages)
}

function overlaps(a: ExamCanvasShapeModel, b: ExamCanvasShapeModel): boolean {
  const ax2 = a.x + a.w
  const ay2 = a.y + a.h
  const bx2 = b.x + b.w
  const by2 = b.y + b.h
  return a.x < bx2 && ax2 > b.x && a.y < by2 && ay2 > b.y
}

function looksUncertainLabel(label: string | undefined): boolean {
  return !label || /\b(unknown|uncertain|maybe|todo|tbd)\b|\?/.test(label.toLowerCase())
}

function addCheapReviewFlags(shapes: ExamCanvasShapeModel[], pages?: CanvasPageGeometry[]): ExamCanvasShapeModel[] {
  const markAreasByQuestion = new Set(shapes.filter((shape) => shape.kind === 'mark_area' && shape.questionId).map((shape) => shape.questionId as string))
  return shapes.map((shape, index) => {
    const flags: string[] = []
    if (shape.source === 'ai' && shape.confirmed === false) flags.push('unconfirmed AI')
    if (typeof shape.confidence === 'number' && shape.confidence < 0.7) flags.push('low confidence')
    if ((shape.kind === 'part' || shape.kind === 'question_number') && looksUncertainLabel(shape.label)) flags.push('uncertain question label')
    if (shape.kind === 'part' && (!shape.maxMarks || shape.maxMarks <= 0) && !markAreasByQuestion.has(shape.questionId ?? shape.id)) flags.push('missing marks')
    const samePageOverlap = shapes.some((other, otherIndex) => otherIndex !== index && shape.kind !== 'boundary' && other.kind !== 'boundary' && pageForShape(shape, pages) === pageForShape(other, pages) && overlaps(shape, other) && (shape.kind === other.kind || (!contains(bounds(shape), bounds(other)) && !contains(bounds(other), bounds(shape)))))
    if (samePageOverlap) flags.push('overlapping shapes')
    return flags.length ? { ...shape, reviewFlags: flags } : shape
  })
}
