#!/usr/bin/env bun
import { readFileSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import { resolve } from 'node:path';

const projectDir = process.cwd();
const envFile = resolve(projectDir, '.env.local');

let raw: string;
try {
  raw = readFileSync(envFile, 'utf8');
} catch {
  console.error(`.env.local not found at ${envFile}`);
  process.exit(1);
}

const vars: Record<string, string> = {};
for (const line of raw.split('\n')) {
  const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
  if (!m) continue;
  let value = m[2];
  if (
    (value.startsWith('"') && value.endsWith('"')) ||
    (value.startsWith("'") && value.endsWith("'"))
  ) {
    value = value.slice(1, -1);
  }
  if (m[1].startsWith('VITE_')) continue;
  vars[m[1]] = value;
}

const keys = Object.keys(vars);
if (keys.length === 0) {
  console.log('No non-VITE_ variables found in .env.local — nothing to sync.');
  process.exit(0);
}

console.log(`Syncing ${keys.length} variable(s) to Vercel (development): ${keys.join(', ')}`);

for (const key of keys) {
  spawnSync('npx', ['vercel', 'env', 'rm', key, 'development', '--yes'], {
    cwd: projectDir,
    stdio: ['ignore', 'ignore', 'ignore'],
  });
  const add = spawnSync('npx', ['vercel', 'env', 'add', key, 'development'], {
    cwd: projectDir,
    input: vars[key],
    stdio: ['pipe', 'inherit', 'inherit'],
  });
  if (add.status !== 0) {
    console.error(`Failed to add ${key}`);
    process.exit(1);
  }
}

console.log(`✅ Synced ${keys.length} variable(s).`);
