import express from 'express';
import { getClient, isClientReady } from '../services/aiService.js';

const router = express.Router();

const subscribers = new Set();
let sdkStream = null;
let sdkAbortController = null;

function startSdkStream() {
  if (sdkStream) return;
  if (!isClientReady()) return;

  const sdk = getClient();
  sdkAbortController = new AbortController();

  sdk.event.subscribe({ signal: sdkAbortController.signal })
    .then((result) => {
      sdkStream = result.stream;
      (async () => {
        try {
          for await (const event of sdkStream) {
            if (sdkAbortController.signal.aborted) break;
            broadcast(event);
          }
        } catch (err) {
          if (err.name !== 'AbortError') {
            console.error('[SSE Proxy] SDK stream error:', err.message);
          }
        } finally {
          sdkStream = null;
        }
      })();
    })
    .catch((err) => {
      console.error('[SSE Proxy] SDK subscribe error:', err.message);
      sdkStream = null;
    });
}

function stopSdkStream() {
  if (sdkAbortController) {
    sdkAbortController.abort();
    sdkAbortController = null;
  }
  sdkStream = null;
}

function broadcast(event) {
  const eventName = event.type || 'message';
  const { type, ...data } = event;
  const eventData = JSON.stringify(data);
  const message = `event: ${eventName}\ndata: ${eventData}\n\n`;

  if (event.type === 'question.asked') {
    console.log('[SSE] question.asked event, data:', eventData.substring(0, 500));
  }

  for (const sub of subscribers) {
    try {
      sub.res.write(message);
    } catch (e) {
      subscribers.delete(sub);
    }
  }

  if (event.type === 'question.asked') {
    const aliasMessage = `event: question\ndata: ${eventData}\n\n`;
    for (const sub of subscribers) {
      try {
        sub.res.write(aliasMessage);
      } catch (e) {
        subscribers.delete(sub);
      }
    }
  }

  if (subscribers.size === 0) {
    stopSdkStream();
  }
}

router.get('/', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  res.setHeader('X-Accel-Buffering', 'no');
  res.flushHeaders();

  const sub = { res };
  subscribers.add(sub);

  res.write(`event: connected\ndata: {}\n\n`);

  startSdkStream();

  const cleanup = () => {
    subscribers.delete(sub);
    if (subscribers.size === 0) {
      stopSdkStream();
    }
  };

  req.on('close', cleanup);
  res.on('close', cleanup);
});

router.post('/test/question', (req, res) => {
  const sessionId = req.body?.sessionId || null;
  const msgId = `test-msg-${Date.now()}`;
  const partId = `test-part-${Date.now()}`;

  if (!subscribers.size) {
    return res.status(400).json({ error: 'No SSE subscribers connected. Please open the UI first.' });
  }

  const textEvent = {
    type: 'message.part.updated',
    part: {
      id: partId,
      type: 'text',
      text: '我需要向你确认一些信息：',
      sessionID: sessionId,
      messageID: msgId,
    },
    sessionID: sessionId,
  };

  const questionEvent = {
    type: 'message.part.updated',
    part: {
      id: `qpart-${Date.now()}`,
      type: 'tool',
      tool: 'question',
      sessionID: sessionId,
      messageID: msgId,
      state: {
        input: {
          questions: [
            {
              header: '技术选型',
              question: '你希望使用哪种前端框架来构建项目？',
              options: [
                { label: 'React', description: '使用 React 框架' },
                { label: 'Vue', description: '使用 Vue 框架' },
                { label: 'Angular', description: '使用 Angular 框架' },
              ],
            },
            {
              header: '样式方案',
              question: '你偏好哪种 CSS 方案？',
              options: [
                { label: 'Tailwind CSS', description: '使用 Tailwind CSS' },
                { label: 'CSS Modules', description: '使用 CSS Modules' },
                { label: 'Styled Components', description: '使用 Styled Components' },
              ],
            },
          ],
        },
      },
    },
    sessionID: sessionId,
  };

  broadcast(textEvent);

  setTimeout(() => {
    broadcast(questionEvent);
  }, 500);

  res.json({ ok: true, sessionId, msgId, hint: 'Question event sent. Check the UI for the question card.' });
});

export { router as sseRouter };
