import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { existsSync } from 'fs';

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

export const TEMPLATES = {
  'browser-test-automation': {
    name: 'browser-test-automation',
    displayName: 'Browser Test Automation (Full Workflow)',
    description: 'Complete browser test automation workflow with title generation, live execution, and script generation',
    path: join(__dirname, 'browser-test-automation'),
    default: true,
    features: [
      'Preflight analysis: extract title + assertion checklist from spec',
      'Execute test live with AI + browser (Claude or Cursor)',
      'Generate Playwright script with stable IDs',
      'Real-time streaming output',
      'Video recording of browser sessions'
    ]
  }
};

export class TemplateFactory {
  static listTemplates() {
    return Object.values(TEMPLATES);
  }

  static getDefault() {
    return Object.values(TEMPLATES).find(t => t.default) || TEMPLATES['browser-test-automation'];
  }

  static getTemplate(name) {
    const template = TEMPLATES[name];
    if (!template) {
      const available = Object.keys(TEMPLATES).join(', ');
      throw new Error(`Template "${name}" not found. Available: ${available}`);
    }
    return template;
  }

  static validateTemplate(templatePath) {
    const requiredFiles = ['graph.mjs', 'nodes', 'README.md'];
    
    for (const file of requiredFiles) {
      const filePath = join(templatePath, file);
      if (!existsSync(filePath)) {
        throw new Error(`Template missing required file: ${file}`);
      }
    }
    
    return true;
  }

  static getTemplateFiles(templateName) {
    const template = this.getTemplate(templateName);
    this.validateTemplate(template.path);
    
    const resultHandlerPath = join(template.path, 'result-handler.mjs');
    return {
      graphPath: join(template.path, 'graph.mjs'),
      nodesPath: join(template.path, 'nodes'),
      readmePath: join(template.path, 'README.md'),
      resultHandlerPath: existsSync(resultHandlerPath) ? resultHandlerPath : null,
      template
    };
  }

  static registerCustomTemplate(name, config) {
    if (TEMPLATES[name]) {
      throw new Error(`Template "${name}" already exists`);
    }
    
    if (!config.path || !config.displayName) {
      throw new Error('Custom template must have "path" and "displayName"');
    }
    
    this.validateTemplate(config.path);
    
    TEMPLATES[name] = {
      name,
      displayName: config.displayName,
      description: config.description || '',
      path: config.path,
      features: config.features || [],
      custom: true
    };
    
    return TEMPLATES[name];
  }
}

export default TemplateFactory;
