import { spawn } from 'child_process';
import * as path from 'path';
import { config } from '../../config';
import { logger } from '../../utils/logger';

class PythonServiceManager {
  private pythonProcess: any = null;
  private isRunning: boolean = false;

  async start(): Promise<boolean> {
    if (this.isRunning) {
      logger.log('Python服务已经在运行');
      return true;
    }

    try {
      // 构建Python服务的路径
      const pythonServicePath = path.join(__dirname, '../../../python_service/main.py');
      
      // 从配置中读取端口，默认3007
      const port = config.dataSource?.tqsdk?.pythonPort || 3007;
      
      logger.log(`启动Python TQAPI服务，端口: ${port}...`);
      
      // 启动Python服务，传递端口参数
      this.pythonProcess = spawn('python', [pythonServicePath, '--port', port.toString()], {
        cwd: path.join(__dirname, '../../../python_service'),
        stdio: 'inherit',
        shell: true
      });

      this.pythonProcess.on('error', (error: any) => {
        logger.error('启动Python服务失败:', error);
        this.isRunning = false;
      });

      this.pythonProcess.on('exit', (code: number, signal: string) => {
        logger.log(`Python服务退出，代码: ${code}, 信号: ${signal}`);
        this.isRunning = false;
      });

      // 等待2秒，确保Python服务有时间启动
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      this.isRunning = true;
      logger.log('Python TQAPI服务启动成功');
      return true;
    } catch (error) {
      logger.error('启动Python服务时出错:', error);
      this.isRunning = false;
      return false;
    }
  }

  stop(): void {
    if (this.pythonProcess) {
      try {
        logger.log('停止Python TQAPI服务...');
        // 发送终止信号
        this.pythonProcess.kill();
        // 等待进程退出
        this.pythonProcess.on('exit', (code: number, signal: string) => {
          logger.log(`Python服务退出，代码: ${code}, 信号: ${signal}`);
        });
        this.pythonProcess = null;
        this.isRunning = false;
        logger.log('Python TQAPI服务已停止');
      } catch (error) {
        logger.error('停止Python服务时出错:', error);
        this.pythonProcess = null;
        this.isRunning = false;
      }
    } else {
      logger.log('Python服务未运行，无需停止');
    }
  }

  getStatus(): boolean {
    return this.isRunning;
  }
}

// 导出单例实例
export const pythonServiceManager = new PythonServiceManager();
