import { statSync } from 'fs';
import { readFileSync, writeFileSync } from 'fs';
import { join } from 'path';

// Get image modification times
const sidebarBgPath = join(process.cwd(), 'public', 'sidebar-background.jpg');
const logoPath = join(process.cwd(), 'public', 'seera-logo.png');
const sidebarPath = join(process.cwd(), 'src', 'components', 'Sidebar.tsx');
const loginPath = join(process.cwd(), 'src', 'pages', 'Login.tsx');
const indexPath = join(process.cwd(), 'index.html');

try {
  // Get sidebar background image modification time
  const sidebarBgStats = statSync(sidebarBgPath);
  const sidebarBgMtime = Math.floor(sidebarBgStats.mtimeMs / 1000);
  
  // Get logo modification time
  const logoStats = statSync(logoPath);
  const logoMtime = Math.floor(logoStats.mtimeMs / 1000);
  
  // Update Sidebar.tsx
  let sidebarContent = readFileSync(sidebarPath, 'utf8');
  
  // Update sidebar background version constant
  sidebarContent = sidebarContent.replace(
    /(const imageVersion = import\.meta\.env\.DEV[\s\S]*?`\?v=)([\d]+)(`; \/\/ Auto-updated by build script)/,
    `$1${sidebarBgMtime}$3`
  );
  
  // Update logo version constant
  sidebarContent = sidebarContent.replace(
    /(const logoVersion = import\.meta\.env\.DEV[\s\S]*?`\?v=)([\d]+)(`; \/\/ Auto-updated by build script)/,
    `$1${logoMtime}$3`
  );
  
  writeFileSync(sidebarPath, sidebarContent, 'utf8');
  console.log(`✓ Updated sidebar background image version to ${sidebarBgMtime}`);
  console.log(`✓ Updated seera-logo.png version to ${logoMtime} in Sidebar.tsx`);
  
  // Update Login.tsx
  let loginContent = readFileSync(loginPath, 'utf8');
  
  // Update logo version constant
  loginContent = loginContent.replace(
    /(const logoVersion = import\.meta\.env\.DEV[\s\S]*?`\?v=)([\d]+)(`; \/\/ Auto-updated by build script)/,
    `$1${logoMtime}$3`
  );
  
  writeFileSync(loginPath, loginContent, 'utf8');
  console.log(`✓ Updated seera-logo.png version to ${logoMtime} in Login.tsx`);
  
  // Update index.html favicon
  let indexContent = readFileSync(indexPath, 'utf8');
  
  // Update favicon version
  indexContent = indexContent.replace(
    /seera-logo\.png(\?v=[\d]+)?/g,
    `seera-logo.png?v=${logoMtime}`
  );
  
  writeFileSync(indexPath, indexContent, 'utf8');
  console.log(`✓ Updated seera-logo.png version to ${logoMtime} in index.html`);
  
} catch (error) {
  console.warn('⚠ Could not update image versions:', error.message);
}
