import fs from 'fs';

let basePathRaw = process.env['VITE_BASEPATH'] || '';

// If env not provided, try to detect a <base href="..."> in the
// built client's index.html (if present). This helps when the
// client has been built with a base like '/ketr.ketran' but the
// server was started without VITE_BASEPATH set.
if (!basePathRaw) {
  try {
    const indexPath = 'client/build/index.html';
    if (fs.existsSync(indexPath)) {
      const content = fs.readFileSync(indexPath, 'utf8');
      const m = content.match(/<base[^>]*href=["']([^"']+)["']/i);
      if (m && m[1]) {
        // Strip leading/trailing slashes for normalization below
        basePathRaw = m[1].replace(/^\/+/, '').replace(/\/+$/, '');
        // If base was just '/', treat as empty
        if (basePathRaw === '') basePathRaw = '';
        console.log(`Detected client build base href '${m[1]}' and using VITE_BASEPATH='${basePathRaw}'`);
      }
    }
  } catch (err) {
    // ignore and fall back to default
  }
}

let basePath = '/' + (basePathRaw || '').replace(/^\/+/, '').replace(/\/+$/, '') + '/';
if (basePath === '//') basePath = '/';

console.log(`Using basepath ${basePath}`);

export default basePath;
