export const CURRENT_COMPATIBILITY_DATE = "2026-08-02";
export const CURRENT_FRAMEWORK_BEHAVIOUR = 1;

export interface CompatibilityPolicy {
  compatibilityDate?: string;
  frameworkBehaviour?: number;
}

export interface CompatibilityReport {
  configuredDate?: string;
  effectiveDate: string;
  currentDate: string;
  configuredBehaviour?: number;
  effectiveBehaviour: number;
  currentBehaviour: number;
  needsUpgrade: boolean;
  future: boolean;
  messages: string[];
}

export function isCompatibilityDate(value: string): boolean {
  if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
  const date = new Date(`${value}T00:00:00.000Z`);
  return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
}

export function resolveCompatibility(policy: CompatibilityPolicy): CompatibilityReport {
  const configuredDate = policy.compatibilityDate;
  const configuredBehaviour = policy.frameworkBehaviour;
  const effectiveDate = configuredDate ?? "1970-01-01";
  const effectiveBehaviour = configuredBehaviour ?? 0;
  const future =
    (configuredDate !== undefined && configuredDate > CURRENT_COMPATIBILITY_DATE) ||
    (configuredBehaviour !== undefined && configuredBehaviour > CURRENT_FRAMEWORK_BEHAVIOUR);
  const needsUpgrade =
    !future &&
    (effectiveDate < CURRENT_COMPATIBILITY_DATE ||
      effectiveBehaviour < CURRENT_FRAMEWORK_BEHAVIOUR);
  const messages: string[] = [];
  if (!configuredDate) messages.push("compatibilityDate is not configured; legacy defaults apply.");
  if (!configuredBehaviour)
    messages.push("frameworkBehaviour is not configured; behaviour version 0 applies.");
  if (future)
    messages.push("Configuration targets framework behavior newer than this CLI supports.");
  else if (needsUpgrade)
    messages.push("A newer compatibility policy is available; review it before upgrading.");
  else messages.push("Compatibility policy matches the current framework behavior.");
  return {
    configuredDate,
    effectiveDate,
    currentDate: CURRENT_COMPATIBILITY_DATE,
    configuredBehaviour,
    effectiveBehaviour,
    currentBehaviour: CURRENT_FRAMEWORK_BEHAVIOUR,
    needsUpgrade,
    future,
    messages,
  };
}
