/**
 * Windsurf Workflow 测试
 * 使用新的TypeScript架构测试旧的YAML workflow
 */

import * as fs from 'fs';
import * as path from 'path';
import * as yaml from 'js-yaml';
import { AdsPowerProvider } from '../src/providers/adspower/AdsPowerProvider';
import { WorkflowEngine } from '../src/workflow/WorkflowEngine';

interface WindsurfConfig {
  site: string;
  workflow: any[];
  errorHandling?: any;
}

async function runWindsurfWorkflow() {
  console.log('🚀 Starting Windsurf Workflow Test...\n');

  // 1. 读取YAML配置
  const configPath = path.join(__dirname, '../configs/sites/windsurf.yaml');
  console.log(`📄 Loading config from: ${configPath}`);
  
  if (!fs.existsSync(configPath)) {
    console.error('❌ Config file not found!');
    console.log('Please copy windsurf.yaml to: browser-automation-ts/configs/sites/windsurf.yaml');
    process.exit(1);
  }

  const configContent = fs.readFileSync(configPath, 'utf8');
  const config = yaml.load(configContent) as WindsurfConfig;
  
  console.log(`✅ Loaded workflow with ${config.workflow.length} steps\n`);

  // 2. 初始化AdsPower Provider
  console.log('🌐 Initializing AdsPower Provider...');
  const provider = new AdsPowerProvider({
    profileId: process.env.ADSPOWER_USER_ID,
    siteName: 'Windsurf'
  });

  try {
    // 3. 启动浏览器
    const result = await provider.launch();
    console.log('✅ Browser launched successfully\n');

    // 4. 准备Context
    const context = {
      page: result.page,
      browser: result.browser,
      logger: console,
      data: {
        // 可以从环境变量或其他地方加载账号数据
        account: {
          email: process.env.WINDSURF_EMAIL || 'test@example.com',
          password: process.env.WINDSURF_PASSWORD || 'password123'
        }
      },
      siteConfig: {
        url: 'https://codeium.com',
        name: 'Windsurf'
      },
      config: config,
      siteName: 'Windsurf'
    };

    // 5. 创建WorkflowEngine
    const engine = new WorkflowEngine(
      config.workflow,
      context,
      provider.getActionFactory()
    );

    // 6. 执行Workflow
    console.log('▶️  Starting workflow execution...\n');
    const workflowResult = await engine.execute();

    // 7. 输出结果
    console.log('\n' + '='.repeat(60));
    console.log('📊 Workflow Execution Summary');
    console.log('='.repeat(60));
    console.log(`Status: ${workflowResult.success ? '✅ SUCCESS' : '❌ FAILED'}`);
    console.log(`Steps Completed: ${workflowResult.steps}/${config.workflow.length}`);
    console.log(`Duration: ${(workflowResult.duration / 1000).toFixed(2)}s`);
    console.log(`Errors: ${workflowResult.errors.length}`);
    
    if (workflowResult.errors.length > 0) {
      console.log('\n❌ Errors:');
      workflowResult.errors.forEach((err: any, i: number) => {
        console.log(`  ${i + 1}. Step ${err.step} (${err.name}): ${err.error}`);
      });
    }
    console.log('='.repeat(60) + '\n');

    // 8. 等待查看结果
    console.log('⏸️  Waiting 5 seconds before closing...');
    await new Promise(resolve => setTimeout(resolve, 5000));

  } catch (error: any) {
    console.error('\n❌ Fatal error:', error.message);
    console.error(error.stack);
  } finally {
    // 9. 关闭浏览器
    try {
      console.log('\n🔒 Closing browser...');
      await provider.close();
      console.log('✅ Browser closed successfully');
    } catch (e: any) {
      console.error('⚠️  Error closing browser:', e.message);
    }
  }
}

// 运行测试
runWindsurfWorkflow()
  .then(() => {
    console.log('\n✅ Test completed!');
    process.exit(0);
  })
  .catch((error) => {
    console.error('\n❌ Test failed:', error);
    process.exit(1);
  });
