import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import * as dotenv from 'dotenv';

// Brand files to sync
const FILES: Record<string, string> = {
  'logo.png': 'src/assets/brand/logo.png',
  'icon.png': 'src/assets/brand/icon.png',
  'favicon.ico': 'public/favicon.ico',
};

// Get mode from CLI args: --mode development | production
const modeArg = process.argv.indexOf('--mode');
const mode =
  modeArg !== -1 && process.argv[modeArg + 1]
    ? process.argv[modeArg + 1]
    : 'development';

// Load environment variables from correct .env file
dotenv.config({ path: `.env.${mode}` });
const sourceDir = process.env.VITE_APP_BRAND_IMAGE_SOURCE_DIR;
if (!sourceDir) {
  console.error(
    `[sync-brand-assets] VITE_APP_BRAND_IMAGE_SOURCE_DIR is not defined in .env.${mode}`
  );
  process.exit(1);
}

// Utility: hash a file
function hashFile(filePath: string): string | null {
  if (!fs.existsSync(filePath)) {
    return null;
  }
  const data = fs.readFileSync(filePath);
  return crypto.createHash('sha256').update(data).digest('hex');
}

// Copy file if different
function copyIfDifferent(src: string, dest: string) {
  if (!fs.existsSync(src)) {
    console.error(`[sync-brand-assets] Source file not found: ${src}`);
    process.exit(1);
  }

  const srcHash = hashFile(src);
  const destHash = hashFile(dest);

  if (srcHash !== destHash) {
    fs.mkdirSync(path.dirname(dest), { recursive: true });
    fs.copyFileSync(src, dest);
    console.log(`[sync-brand-assets] Copied: ${path.basename(src)} -> ${dest}`);
  } else {
    console.log(
      `[sync-brand-assets] Skipped (unchanged): ${path.basename(src)}`
    );
  }
}

// Main
console.log(`[sync-brand-assets] Using .env.${mode} (sourceDir=${sourceDir})`);
for (const [file, dest] of Object.entries(FILES)) {
  const src = path.resolve(sourceDir, file);
  const dst = path.resolve(process.cwd(), dest);
  copyIfDifferent(src, dst);
}
