import { z } from 'zod'

/**
 * Developer task board (Nash, 2026-10-21).
 *
 * "Communication with the developer, I would like to have it through the
 * board." The CTO posts a task with everything the developer needs (what,
 * why, the steps in order, done-when, what to report); the developer moves
 * it from pending to ongoing to completed; the CTO sees the completion
 * instead of reading email. Pure rules, no I/O: the data layer is
 * src/lib/data/dev-tasks.ts.
 */
export const DEV_TASK_STATUSES = ['pending', 'ongoing', 'completed'] as const
export type DevTaskStatus = (typeof DEV_TASK_STATUSES)[number]

export const DEV_TASK_URGENCIES = ['urgent', 'high', 'normal', 'low'] as const
export type DevTaskUrgency = (typeof DEV_TASK_URGENCIES)[number]

export const STATUS_LABELS: Record<DevTaskStatus, string> = { pending: 'Pending', ongoing: 'Ongoing', completed: 'Completed' }
export const URGENCY_LABELS: Record<DevTaskUrgency, string> = { urgent: 'Urgent', high: 'High', normal: 'Normal', low: 'Low' }

/** 0 is the most urgent. */
export function urgencyRank(u: DevTaskUrgency): number {
  return DEV_TASK_URGENCIES.indexOf(u)
}

export interface DevTask {
  id: string
  task_number: number
  project: string
  title: string
  summary: string | null
  urgency: DevTaskUrgency
  status: DevTaskStatus
  position: number
  why: string | null
  steps: string[]
  done_when: string | null
  report_back: string | null
  do_not_touch: string | null
  details: string | null
  due_date: string | null
  source: string
  created_by: string | null
  started_at: string | null
  completed_at: string | null
  completion_note: string | null
  archived_at: string | null
  created_at: string
  updated_at: string
}

export type DevTaskEventAction = 'created' | 'updated' | 'moved' | 'reordered' | 'archived' | 'restored' | 'comment'
export type DevTaskActorKind = 'api' | 'admin' | 'developer'

export interface DevTaskEvent {
  id: string
  task_id: string
  action: DevTaskEventAction
  from_status: string | null
  to_status: string | null
  actor_kind: DevTaskActorKind
  actor_label: string
  detail: Record<string, unknown>
  created_at: string
}

/** "T-12" — the short name used on the card, in comments and on the command line. */
export function taskRef(task: Pick<DevTask, 'task_number'>): string {
  return `T-${task.task_number}`
}

/** A task is addressed by its id or its number ("12", "T-12", "t12"). */
export function parseTaskRef(raw: string): { id: string } | { number: number } | null {
  const value = raw.trim()
  if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) return { id: value.toLowerCase() }
  const m = /^(?:t-?)?(\d{1,9})$/i.exec(value)
  return m ? { number: Number(m[1]) } : null
}

const text = (max: number) => z.string().trim().min(1).max(max)
const optionalText = (max: number) => z.string().trim().max(max).transform((v) => v || null).nullable().optional()

export const devTaskCreateSchema = z.object({
  title: z.string().trim().min(3).max(200),
  project: text(60).default('HHA Workspace'),
  summary: optionalText(500),
  urgency: z.enum(DEV_TASK_URGENCIES).default('normal'),
  why: optionalText(4000),
  steps: z.array(text(2000)).max(40).default([]),
  done_when: optionalText(4000),
  report_back: optionalText(2000),
  do_not_touch: optionalText(2000),
  details: optionalText(20000),
  due_date: z.iso.date().nullable().optional(),
  source: text(60).optional(),
  created_by: optionalText(120),
})
export type DevTaskCreateInput = z.infer<typeof devTaskCreateSchema>

/** What the manager (CTO, API key) may change. Status and order have their own operations. */
export const devTaskUpdateSchema = devTaskCreateSchema.omit({ source: true, created_by: true }).partial().extend({
  status: z.enum(DEV_TASK_STATUSES).optional(),
  completion_note: optionalText(4000),
  archived: z.boolean().optional(),
  /** Place the task right before or after another task in the same column, or at the top or bottom. */
  place: z.union([
    z.object({ before: z.string().trim().min(1).max(64) }),
    z.object({ after: z.string().trim().min(1).max(64) }),
    z.object({ edge: z.enum(['top', 'bottom']) }),
  ]).optional(),
})
export type DevTaskUpdateInput = z.infer<typeof devTaskUpdateSchema>

export const devTaskCommentSchema = z.object({ text: text(4000) })

export type BoardRole = 'manager' | 'developer'

/**
 * Who may move a task where. The manager (Nash, the CTO, an API key) may
 * move anything anywhere. The developer takes a task (pending → ongoing),
 * puts it back (ongoing → pending), finishes it (ongoing → completed), or
 * reopens his own finished task (completed → ongoing).
 */
export function canMove(role: BoardRole, from: DevTaskStatus, to: DevTaskStatus): boolean {
  if (from === to) return true
  if (role === 'manager') return true
  return (from === 'pending' && to === 'ongoing') || (from === 'ongoing' && (to === 'pending' || to === 'completed')) ||
    (from === 'completed' && to === 'ongoing')
}

/** Only the manager edits the brief, reorders inside a column, removes or restores a task. */
export function canEdit(role: BoardRole): boolean {
  return role === 'manager'
}

/** Timestamps that follow a move. Moving back to pending clears both. */
export function statusTimestamps(task: Pick<DevTask, 'started_at' | 'completed_at'>, to: DevTaskStatus, nowIso: string): Pick<DevTask, 'started_at' | 'completed_at'> {
  if (to === 'pending') return { started_at: null, completed_at: null }
  if (to === 'ongoing') return { started_at: task.started_at ?? nowIso, completed_at: null }
  return { started_at: task.started_at ?? nowIso, completed_at: nowIso }
}

const GAP = 1024

/**
 * Where a new task goes in a column: after every task that is at least as
 * urgent, before the first less urgent one. So an urgent task lands at the
 * top (behind other urgent tasks) and a low one at the bottom. `column` must
 * be sorted by position.
 */
export function positionForUrgency(column: readonly Pick<DevTask, 'urgency' | 'position'>[], urgency: DevTaskUrgency): number {
  const rank = urgencyRank(urgency)
  const nextIndex = column.findIndex((t) => urgencyRank(t.urgency) > rank)
  if (nextIndex === -1) return column.length ? column[column.length - 1].position + GAP : GAP
  const next = column[nextIndex].position
  const prev = nextIndex > 0 ? column[nextIndex - 1].position : next - 2 * GAP
  return (prev + next) / 2
}

/** Position for an explicit placement in a column sorted by position (the moving task excluded). */
export function positionForPlacement(
  column: readonly Pick<DevTask, 'id' | 'position'>[],
  place: { before: string } | { after: string } | { edge: 'top' | 'bottom' },
): number | null {
  if (!column.length) return GAP
  if ('edge' in place) return place.edge === 'top' ? column[0].position - GAP : column[column.length - 1].position + GAP
  const targetId = 'before' in place ? place.before : place.after
  const i = column.findIndex((t) => t.id === targetId)
  if (i === -1) return null
  if ('before' in place) return i === 0 ? column[0].position - GAP : (column[i - 1].position + column[i].position) / 2
  return i === column.length - 1 ? column[i].position + GAP : (column[i].position + column[i + 1].position) / 2
}

/**
 * Board order: pending and ongoing by position; completed with the most
 * recently finished first, so the CTO sees the newest completion on top.
 */
export function sortColumn<T extends Pick<DevTask, 'status' | 'position' | 'completed_at' | 'task_number'>>(tasks: readonly T[]): T[] {
  return [...tasks].sort((a, b) => {
    if (a.status === 'completed' && b.status === 'completed') return (b.completed_at ?? '').localeCompare(a.completed_at ?? '') || b.task_number - a.task_number
    return a.position - b.position || a.task_number - b.task_number
  })
}

export function groupByStatus<T extends DevTask>(tasks: readonly T[]): Record<DevTaskStatus, T[]> {
  const live = tasks.filter((t) => !t.archived_at)
  return {
    pending: sortColumn(live.filter((t) => t.status === 'pending')),
    ongoing: sortColumn(live.filter((t) => t.status === 'ongoing')),
    completed: sortColumn(live.filter((t) => t.status === 'completed')),
  }
}

/** Which manager-editable fields actually changed, for the history line. */
export function changedFields(before: Partial<DevTask>, patch: Partial<DevTask>): string[] {
  return Object.keys(patch).filter((k) => JSON.stringify((before as Record<string, unknown>)[k] ?? null) !== JSON.stringify((patch as Record<string, unknown>)[k] ?? null))
}
