export type DerivedSprintStatus = "planning" | "active" | "completed"

const DATE_PREFIX_PATTERN = /^(\d{4})-(\d{2})-(\d{2})/

function parseDateParts(value: string): [number, number, number] | null {
  const match = value.match(DATE_PREFIX_PATTERN)
  if (!match) return null
  return [Number(match[1]), Number(match[2]), Number(match[3])]
}

function asLocalDayDate(value: string, endOfDay: boolean): Date | null {
  const parts = parseDateParts(value)
  if (!parts) return null
  const [year, month, day] = parts
  return endOfDay
    ? new Date(year, month - 1, day, 23, 59, 59, 999)
    : new Date(year, month - 1, day, 0, 0, 0, 0)
}

export function parseSprintStart(value: string): Date {
  const parsed = asLocalDayDate(value, false)
  if (parsed) return parsed
  return new Date(value)
}

export function parseSprintEnd(value: string): Date {
  const parsed = asLocalDayDate(value, true)
  if (parsed) return parsed
  const fallback = new Date(value)
  fallback.setHours(23, 59, 59, 999)
  return fallback
}

export function inferSprintStatusForDateRange(
  startDate: string,
  endDate: string,
  now: Date = new Date()
): DerivedSprintStatus {
  const sprintStart = parseSprintStart(startDate)
  if (now < sprintStart) return "planning"

  const sprintEnd = parseSprintEnd(endDate)
  if (now > sprintEnd) return "completed"

  return "active"
}

export function toLocalDateOnly(now: Date = new Date()): string {
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, "0")
  const day = String(now.getDate()).padStart(2, "0")
  return `${year}-${month}-${day}`
}

export function addDays(date: Date, days: number): Date {
  const next = new Date(date)
  next.setDate(next.getDate() + days)
  return next
}
