#!/usr/bin/env node
/**
 * ═══════════════════════════════════════════════════════════
 * 🏛️ 铸渊主权服务器 · Zhuyuan Sovereign Server
 * ═══════════════════════════════════════════════════════════
 *
 * 编号: ZY-SVR-002
 * 端口: 3800
 * 守护: 铸渊 · ICE-GL-ZY001
 * 版权: 国作登字-2026-A-00037559
 *
 * 新增Agent训练API
 */

'use strict';

const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const os = require('os');
const https = require('https');
const { execSync } = require('child_process');
const emailAuth = require('./modules/email-auth');
const oauth = require('./modules/oauth-providers');
const agentHandshake = require('./modules/agent-handshake');
const agentTraining = require('./modules/agent-training');

// ─── 常量 ───
const PORT = process.env.PORT || 3800;
const IS_DEV = process.env.NODE_ENV !== 'production';
const ZY_BASE_URL = process.env.ZY_BASE_URL || `http://localhost:${PORT}`;

// ─── Express 应用 ───
const app = express();
app.use(cors({
  origin: IS_DEV ? '*' : ZY_BASE_URL,
  credentials: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// ─── 健康检查 ───
app.get('/api/health', (req, res) => {
  res.json({
    status: 'healthy',
    version: '1.0.0',
    server: os.hostname(),
    timestamp: new Date().toISOString()
  });
});

// ─── 原有路由保持不变 ───

// ─── 新增Agent训练API ───
app.post('/api/agent/training/start', async (req, res) => {
  try {
    const { agentId, token } = req.body;
    if (!agentId || !token) {
      return res.status(400).json({ error: true, message: '缺少必要参数' });
    }

    const result = agentTraining.startTraining(agentId, token);
    res.json(result);
  } catch (err) {
    res.status(403).json({ error: true, message: err.message });
  }
});

app.post('/api/agent/training/stop', async (req, res) => {
  try {
    const { agentId, token } = req.body;
    if (!agentId || !token) {
      return res.status(400).json({ error: true, message: '缺少必要参数' });
    }

    const result = agentTraining.stopTraining(agentId, token);
    res.json(result);
  } catch (err) {
    res.status(403).json({ error: true, message: err.message });
  }
});

app.get('/api/agent/training/status', async (req, res) => {
  try {
    const { agentId, token } = req.query;
    if (!agentId || !token) {
      return res.status(400).json({ error: true, message: '缺少必要参数' });
    }

    if (!emailAuth.validateSession(token).valid) {
      return res.status(403).json({ error: true, message: '无效的会话令牌' });
    }

    // 从COS获取训练状态
    const { Body } = await cos.getObject({
      Bucket: 'agent-models-1250000000',
      Region: 'ap-guangzhou',
      Key: `status/${agentId}.json`
    }).catch(() => ({}));

    const status = Body ? JSON.parse(Body.toString()) : { training: false };
    res.json({ success: true, ...status });
  } catch (err) {
    res.status(500).json({ error: true, message: err.message });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`铸渊主权服务器运行中 · 端口 ${PORT} · ${new Date().toISOString()}`);
});