import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export function ensureDirectories() {
  const dirs = [
    process.env.UPLOAD_DIR || './uploads',
    process.env.DOWNLOAD_DIR || './downloads'
  ];
  
  dirs.forEach(dir => {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
      console.log(`✓ Created directory: ${dir}`);
    }
  });
}

export function cleanupOldFiles(dir, ageHours = 24) {
  if (!fs.existsSync(dir)) return;
  
  const now = Date.now();
  const ageMs = ageHours * 60 * 60 * 1000;
  
  fs.readdirSync(dir).forEach(file => {
    const filepath = path.join(dir, file);
    const stats = fs.statSync(filepath);
    
    if (now - stats.mtimeMs > ageMs) {
      try {
        fs.unlinkSync(filepath);
        console.log(`✓ Cleaned up old file: ${file}`);
      } catch (err) {
        console.error(`Error cleaning up ${file}:`, err);
      }
    }
  });
}

export function getProjectRoot() {
  return path.dirname(__dirname);
}

export function joinPath(...parts) {
  return parts
    .filter(Boolean)
    .map(p => String(p).replace(/^\/+|\/+$/g, ''))
    .filter(p => p.length > 0)
    .join('/')
    + (String(parts[parts.length - 1]).endsWith('/') ? '/' : '');
}

export function normalizeEndpoint(ep) {
  if (!ep) return '';
  return ep.endsWith('/') ? ep : ep + '/';
}

export function sanitizeFilename(filename) {
  return filename
    .replace(/[^a-zA-Z0-9._-]/g, '_')
    .substring(0, 255);
}

export async function loadVendorLibs() {
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
  const projectRoot = path.dirname(__dirname);
  
  try {
    const wrapperPath = path.join(projectRoot, 'vendor', 'xapiwrapper.min.js');
    const gluePath = path.join(projectRoot, 'vendor', 'xAPI.js');
    
    const wrapper = fs.readFileSync(wrapperPath, 'utf-8');
    const glue = fs.readFileSync(gluePath, 'utf-8');
    
    return { wrapper, glue };
  } catch (err) {
    throw new Error(`Failed to load vendor libraries: ${err.message}`);
  }
}
