/**
 * 提示词优化服务
 * 调用后端 API 优化用户输入的提示词
 */

import * as vscode from 'vscode';
import * as https from 'https';
import * as http from 'http';
import { URL } from 'url';
import { getApiUrl } from '../config/settings';

/** 优化响应类型 */
interface OptimizeResponse {
  success: boolean;
  optimizedPrompt?: string;
  error?: string;
}

/**
 * 优化提示词
 * @param prompt 原始提示词
 * @returns 优化后的提示词
 */
export async function optimizePrompt(prompt: string): Promise<string> {
  // 获取 JWT token
  const session = await vscode.authentication.getSession('iccoder', [], { silent: true });
  if (!session?.accessToken) {
    throw new Error('未登录，请先登录');
  }

  const response = await callOptimizeApi(prompt, session.accessToken);

  if (response.success && response.optimizedPrompt) {
    return response.optimizedPrompt;
  } else {
    throw new Error(response.error || '优化失败');
  }
}

/**
 * 调用后端优化 API
 */
async function callOptimizeApi(prompt: string, token: string): Promise<OptimizeResponse> {
  const urlStr = getApiUrl('/api/prompt/optimize');
  const url = new URL(urlStr);

  const isHttps = url.protocol === 'https:';
  const httpModule = isHttps ? https : http;

  const body = JSON.stringify({ prompt });

  const requestOptions: http.RequestOptions = {
    hostname: url.hostname,
    port: url.port || (isHttps ? 443 : 80),
    path: url.pathname + url.search,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(body),
      'Authorization': `Bearer ${token}`
    },
    timeout: 30000
  };

  return new Promise((resolve, reject) => {
    const req = httpModule.request(requestOptions, (res) => {
      let data = '';

      res.on('data', (chunk) => {
        data += chunk;
      });

      res.on('end', () => {
        console.log('[PromptOptimize] 响应状态码:', res.statusCode);

        try {
          const json = JSON.parse(data);
          if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
            resolve(json as OptimizeResponse);
          } else if (res.statusCode === 401 || res.statusCode === 403) {
            resolve({ success: false, error: '登录已过期，请重新登录' });
          } else {
            resolve({ success: false, error: json.error || json.message || `HTTP ${res.statusCode}` });
          }
        } catch (e) {
          resolve({ success: false, error: `解析响应失败: ${data}` });
        }
      });
    });

    req.on('error', (error) => {
      reject(error);
    });

    req.on('timeout', () => {
      req.destroy();
      reject(new Error('请求超时'));
    });

    req.write(body);
    req.end();
  });
}
