/**
 * 轻量级Operation-Agent客户端
 * 支持Windows/Linux，可打包为单个exe文件
 * 通过WebSocket与前端通信，执行浏览器自动化操作
 */

import { WebSocketServer, WebSocket } from 'ws';
import { chromium, Browser, Page } from 'playwright';
import { createServer } from 'http';
import * as path from 'path';
import * as os from 'os';

interface ClientConfig {
  port: number;
  headless: boolean;
  proxy?: string;
}

interface Command {
  type: 'authorize' | 'getProducts' | 'updatePrice' | 'getOrders';
  platform: string;
  data: any;
}

interface Response {
  success: boolean;
  data?: any;
  error?: string;
}

export class LightweightClient {
  private config: ClientConfig;
  private wss: WebSocketServer;
  private browser: Browser | null = null;
  private activePages: Map<string, Page> = new Map();

  constructor(config: ClientConfig) {
    this.config = config;
    
    // 创建HTTP服务器用于健康检查
    const server = createServer((req, res) => {
      if (req.url === '/health') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ 
          status: 'ok', 
          platform: os.platform(),
          version: '1.0.0'
        }));
      } else {
        res.writeHead(404);
        res.end();
      }
    });

    // 创建WebSocket服务器
    this.wss = new WebSocketServer({ server });
    server.listen(config.port);

    this.setupWebSocketHandlers();
  }

  private setupWebSocketHandlers() {
    this.wss.on('connection', (ws: WebSocket) => {
      console.log('客户端连接建立');
      
      ws.on('message', async (data: Buffer) => {
        try {
          const command: Command = JSON.parse(data.toString());
          const response = await this.handleCommand(command);
          ws.send(JSON.stringify(response));
        } catch (error) {
          ws.send(JSON.stringify({
            success: false,
            error: error instanceof Error ? error.message : '未知错误'
          }));
        }
      });

      ws.on('close', () => {
        console.log('客户端连接关闭');
      });
    });
  }

  private async handleCommand(command: Command): Promise<Response> {
    try {
      switch (command.type) {
        case 'authorize':
          return await this.authorizePlatform(command.platform, command.data);
        case 'getProducts':
          return await this.getProducts(command.platform, command.data);
        case 'updatePrice':
          return await this.updateProductPrice(command.platform, command.data);
        case 'getOrders':
          return await this.getOrders(command.platform, command.data);
        default:
          return { success: false, error: '未知命令类型' };
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '执行命令失败'
      };
    }
  }

  private async authorizePlatform(platform: string, authData: any): Promise<Response> {
    if (!this.browser) {
      this.browser = await chromium.launch({ 
        headless: this.config.headless,
        proxy: this.config.proxy ? { server: this.config.proxy } : undefined
      });
    }

    const page = await this.browser.newPage();
    const pageId = `${platform}_${Date.now()}`;
    this.activePages.set(pageId, page);

    // 根据平台执行授权逻辑
    const result = await this.performPlatformAuthorization(platform, page, authData);
    
    return {
      success: result.success,
      data: { pageId, ...result.data }
    };
  }

  private async performPlatformAuthorization(platform: string, page: Page, authData: any) {
    // 简化的平台授权逻辑
    switch (platform) {
      case 'tiktok':
        await page.goto('https://seller.tiktok.com');
        // TikTok授权逻辑
        return { success: true, data: { message: 'TikTok授权成功' } };
      case 'shopee':
        await page.goto('https://seller.shopee.com');
        // Shopee授权逻辑
        return { success: true, data: { message: 'Shopee授权成功' } };
      default:
        return { success: false, error: '不支持的平台' };
    }
  }

  private async getProducts(platform: string, data: any): Promise<Response> {
    const { pageId, limit = 10 } = data;
    const page = this.activePages.get(pageId);
    
    if (!page) {
      return { success: false, error: '页面未找到' };
    }

    // 模拟获取商品列表
    const products = [
      { id: '1', name: '商品1', price: 100, stock: 50 },
      { id: '2', name: '商品2', price: 200, stock: 30 }
    ].slice(0, limit);

    return { success: true, data: { products } };
  }

  private async updateProductPrice(platform: string, data: any): Promise<Response> {
    const { pageId, productId, newPrice } = data;
    const page = this.activePages.get(pageId);
    
    if (!page) {
      return { success: false, error: '页面未找到' };
    }

    // 模拟更新价格操作
    console.log(`更新商品 ${productId} 价格为 ${newPrice}`);
    
    return { success: true, data: { message: '价格更新成功' } };
  }

  private async getOrders(platform: string, data: any): Promise<Response> {
    const { pageId, limit = 10 } = data;
    const page = this.activePages.get(pageId);
    
    if (!page) {
      return { success: false, error: '页面未找到' };
    }

    // 模拟获取订单列表
    const orders = [
      { id: '1', orderNumber: 'ORDER001', status: 'pending', amount: 100 },
      { id: '2', orderNumber: 'ORDER002', status: 'shipped', amount: 200 }
    ].slice(0, limit);

    return { success: true, data: { orders } };
  }

  async start() {
    console.log(`轻量级客户端启动在端口 ${this.config.port}`);
    console.log(`健康检查: http://localhost:${this.config.port}/health`);
    console.log('等待前端连接...');
  }

  async stop() {
    if (this.browser) {
      await this.browser.close();
    }
    this.wss.close();
    console.log('客户端已停止');
  }
}

// 命令行启动
if (require.main === module) {
  const config: ClientConfig = {
    port: process.env.PORT ? parseInt(process.env.PORT) : 8080,
    headless: process.env.HEADLESS !== 'false',
    proxy: process.env.PROXY || undefined
  };

  const client = new LightweightClient(config);
  client.start();

  // 优雅关闭
  process.on('SIGINT', async () => {
    console.log('收到关闭信号，正在停止客户端...');
    await client.stop();
    process.exit(0);
  });
}