#!/usr/bin/env node
import fs from 'fs';
import path from 'path';

const cmd = process.argv[2] || 'set';
const repoRoot = process.cwd();
const dst = path.join(repoRoot, 'src', 'build-info.json');

function getPackageVersion() {
  try {
    const pkgPath = path.join(repoRoot, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
    return pkg && pkg.version ? String(pkg.version) : null;
  } catch (_) {
    return null;
  }
}

function computeDebugFlag() {
  const envVal = process.env.RADIO_DEBUG_DEVTOOLS;
  if (envVal === '1' || envVal === 'true') return true;
  const arg = (process.argv[3] || '').toLowerCase();
  return arg === 'debug' || arg === '--debug';
}

if (cmd === 'set') {
  try {
    const version = getPackageVersion();
    const debug = computeDebugFlag();
    const payload = {
      version,
      debug,
      builtAt: new Date().toISOString(),
    };
    fs.writeFileSync(dst, JSON.stringify(payload, null, 2) + '\n', 'utf8');
    console.log(`Wrote build-info.json (debug=${debug}${version ? `, version=${version}` : ''})`);
    process.exit(0);
  } catch (e) {
    console.error('Failed to write build-info.json', e);
    process.exit(1);
  }
} else if (cmd === 'clear') {
  try {
    if (fs.existsSync(dst)) fs.unlinkSync(dst);
    console.log('Removed build-info.json');
    process.exit(0);
  } catch (e) {
    console.error('Failed to remove build-info.json', e);
    process.exit(1);
  }
} else {
  console.error('Unknown command:', cmd);
  process.exit(2);
}
