import type { FeatureFlag } from './types';

const RUNTIME_OVERRIDE_KEY = 'architools:flag-overrides';

export function resolveFlag(
  flag: FeatureFlag,
  envOverrides: Record<string, string>,
  runtimeOverrides: Record<string, boolean>
): boolean {
  // 1. Check environment variable override
  const envKey = `NEXT_PUBLIC_FLAG_${flag.key.toUpperCase().replace(/\./g, '_')}`;
  const envVal = envOverrides[envKey];
  if (envVal !== undefined) {
    return envVal === 'true';
  }

  // 2. Check runtime override
  if (flag.overridable && runtimeOverrides[flag.key] !== undefined) {
    return runtimeOverrides[flag.key]!;
  }

  // 3. Fall back to default
  return flag.enabled;
}

export function resolveAllFlags(
  flags: FeatureFlag[],
  envOverrides: Record<string, string>,
  runtimeOverrides: Record<string, boolean>
): Record<string, boolean> {
  const resolved: Record<string, boolean> = {};

  // First pass: resolve without dependency checks
  for (const flag of flags) {
    resolved[flag.key] = resolveFlag(flag, envOverrides, runtimeOverrides);
  }

  // Second pass: enforce dependencies
  for (const flag of flags) {
    if (resolved[flag.key] && flag.dependencies) {
      for (const dep of flag.dependencies) {
        if (!resolved[dep]) {
          resolved[flag.key] = false;
          break;
        }
      }
    }
  }

  return resolved;
}

export function loadRuntimeOverrides(): Record<string, boolean> {
  if (typeof window === 'undefined') return {};
  try {
    const stored = window.localStorage.getItem(RUNTIME_OVERRIDE_KEY);
    if (stored) return JSON.parse(stored);
  } catch {
    // Ignore parse errors
  }
  return {};
}

export function saveRuntimeOverride(key: string, value: boolean): void {
  if (typeof window === 'undefined') return;
  const overrides = loadRuntimeOverrides();
  overrides[key] = value;
  window.localStorage.setItem(RUNTIME_OVERRIDE_KEY, JSON.stringify(overrides));
}

export function clearRuntimeOverrides(): void {
  if (typeof window === 'undefined') return;
  window.localStorage.removeItem(RUNTIME_OVERRIDE_KEY);
}
