import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import OpenAI from 'openai';
import { MarketService } from '../market/market.service';
import { IndicatorsService } from '../indicators/indicators.service';

export interface AIAnalysisResult {
  summary: string;
  trend: 'bullish' | 'bearish' | 'neutral';
  confidence: number;
  keyFactors: string[];
  supportLevels: number[];
  resistanceLevels: number[];
  recommendation: {
    action: 'buy' | 'sell' | 'hold';
    entryPrice?: number;
    stopLoss?: number;
    targetPrice?: number;
    reasoning: string;
  };
  riskFactors: string[];
}

@Injectable()
export class AiService {
  private readonly logger = new Logger(AiService.name);
  private openai: OpenAI | null = null;

  constructor(
    private readonly configService: ConfigService,
    private readonly marketService: MarketService,
    private readonly indicatorsService: IndicatorsService,
  ) {
    const apiKey = this.configService.get('openai.apiKey');
    if (apiKey) {
      this.openai = new OpenAI({
        apiKey,
        baseURL: this.configService.get('openai.baseURL'),
      });
    }
  }

  /**
   * AI智能分析品种
   */
  async analyzeSymbol(symbol: string): Promise<AIAnalysisResult> {
    try {
      // 获取市场数据
      const [product, klineData, indicators] = await Promise.all([
        this.marketService.getProduct(symbol),
        this.marketService.getKlineData(symbol, '1d', 60),
        this.indicatorsService.calculateAllIndicators(symbol, '1d'),
      ]);

      // 计算技术指标信号
      const technicalSignals = this.analyzeTechnicalIndicators(indicators);

      // 如果有OpenAI API，使用AI分析
      if (this.openai) {
        return await this.analyzeWithAI(symbol, product, klineData, indicators, technicalSignals);
      }

      // 否则使用规则分析
      return this.analyzeWithRules(symbol, product, klineData, indicators, technicalSignals);
    } catch (error) {
      this.logger.error(`AI分析失败 ${symbol}:`, error.message);
      return this.getDefaultAnalysis(symbol);
    }
  }

  /**
   * 使用OpenAI进行分析
   */
  private async analyzeWithAI(
    symbol: string,
    product: any,
    klineData: any[],
    indicators: any,
    technicalSignals: any,
  ): Promise<AIAnalysisResult> {
    const prompt = this.buildAnalysisPrompt(symbol, product, klineData, indicators, technicalSignals);

    try {
      const response = await this.openai!.chat.completions.create({
        model: this.configService.get('openai.model') || 'gpt-4-turbo-preview',
        messages: [
          {
            role: 'system',
            content: '你是一位专业的期货分析师，擅长技术分析和基本面分析。请基于提供的数据给出专业的分析和交易建议。',
          },
          {
            role: 'user',
            content: prompt,
          },
        ],
        temperature: 0.7,
        max_tokens: 2000,
      });

      const content = response.choices[0]?.message?.content;
      if (!content) {
        throw new Error('AI返回空响应');
      }

      return this.parseAIResponse(content, symbol, product);
    } catch (error) {
      this.logger.error('AI分析请求失败:', error.message);
      return this.analyzeWithRules(symbol, product, klineData, indicators, technicalSignals);
    }
  }

  /**
   * 基于规则的分析
   */
  private analyzeWithRules(
    symbol: string,
    product: any,
    klineData: any[],
    indicators: any,
    technicalSignals: any,
  ): AIAnalysisResult {
    const currentPrice = product.price;
    const lastKline = klineData[klineData.length - 1];
    
    // 综合评分
    let bullishScore = 0;
    let bearishScore = 0;

    if (technicalSignals.macd === 'bullish') bullishScore += 2;
    if (technicalSignals.macd === 'bearish') bearishScore += 2;
    
    if (technicalSignals.rsi === 'oversold') bullishScore += 1;
    if (technicalSignals.rsi === 'overbought') bearishScore += 1;
    
    if (technicalSignals.kdj === 'golden_cross') bullishScore += 2;
    if (technicalSignals.kdj === 'dead_cross') bearishScore += 2;

    // 趋势判断
    const trendChange = lastKline.close - klineData[klineData.length - 20].close;
    if (trendChange > 0) bullishScore += 1;
    else bearishScore += 1;

    // 确定整体趋势
    let trend: 'bullish' | 'bearish' | 'neutral' = 'neutral';
    let confidence = 50;

    if (bullishScore > bearishScore) {
      trend = 'bullish';
      confidence = 50 + (bullishScore - bearishScore) * 10;
    } else if (bearishScore > bullishScore) {
      trend = 'bearish';
      confidence = 50 + (bearishScore - bullishScore) * 10;
    }

    confidence = Math.min(confidence, 95);

    // 计算支撑阻力位
    const supportLevels = this.calculateSupportLevels(klineData);
    const resistanceLevels = this.calculateResistanceLevels(klineData);

    // 生成建议
    const recommendation = this.generateRecommendation(
      trend, currentPrice, supportLevels, resistanceLevels, confidence,
    );

    return {
      summary: this.generateSummary(symbol, trend, technicalSignals),
      trend,
      confidence,
      keyFactors: this.generateKeyFactors(technicalSignals),
      supportLevels,
      resistanceLevels,
      recommendation,
      riskFactors: this.generateRiskFactors(trend, technicalSignals),
    };
  }

  /**
   * 分析技术指标信号
   */
  private analyzeTechnicalIndicators(indicators: any): any {
    const signals: any = {};

    // MACD信号
    const macdLast = indicators.macd[indicators.macd.length - 1];
    const macdPrev = indicators.macd[indicators.macd.length - 2];
    if (macdPrev.dif < macdPrev.dea && macdLast.dif > macdLast.dea) {
      signals.macd = 'bullish';
    } else if (macdPrev.dif > macdPrev.dea && macdLast.dif < macdLast.dea) {
      signals.macd = 'bearish';
    } else {
      signals.macd = 'neutral';
    }

    // RSI信号
    const rsiLast = indicators.rsi[indicators.rsi.length - 1];
    signals.rsi = rsiLast.status;

    // KDJ信号
    const kdjLast = indicators.kdj[indicators.kdj.length - 1];
    signals.kdj = kdjLast.signal;

    // 布林带信号
    const bollLast = indicators.bollinger[indicators.bollinger.length - 1];
    signals.bollinger = bollLast.position;

    return signals;
  }

  private buildAnalysisPrompt(
    symbol: string,
    product: any,
    klineData: any[],
    indicators: any,
    signals: any,
  ): string {
    const recentKlines = klineData.slice(-20);
    const currentPrice = product.price;
    
    return `
请分析期货品种 ${symbol} (${product.name}) 的技术面并给出交易建议。

当前价格: ${currentPrice}
涨跌幅: ${product.changePercent}%

最近20日K线数据:
${recentKlines.map(k => 
  `日期: ${k.time}, 开盘: ${k.open}, 最高: ${k.high}, 最低: ${k.low}, 收盘: ${k.close}, 成交量: ${k.volume}`
).join('\n')}

技术指标:
MACD: DIF=${indicators.macd[indicators.macd.length - 1].dif}, DEA=${indicators.macd[indicators.macd.length - 1].dea}
RSI: ${indicators.rsi[indicators.rsi.length - 1].value}
KDJ: K=${indicators.kdj[indicators.kdj.length - 1].k}, D=${indicators.kdj[indicators.kdj.length - 1].d}, J=${indicators.kdj[indicators.kdj.length - 1].j}
布林带: 上轨=${indicators.bollinger[indicators.bollinger.length - 1].upper}, 中轨=${indicators.bollinger[indicators.bollinger.length - 1].middle}, 下轨=${indicators.bollinger[indicators.bollinger.length - 1].lower}

请提供以下分析结果(JSON格式):
{
  "summary": "技术面综述",
  "trend": "bullish/bearish/neutral",
  "confidence": 75,
  "keyFactors": ["关键因素1", "关键因素2"],
  "supportLevels": [支撑位1, 支撑位2],
  "resistanceLevels": [阻力位1, 阻力位2],
  "recommendation": {
    "action": "buy/sell/hold",
    "entryPrice": 建议入场价,
    "stopLoss": 止损价,
    "targetPrice": 目标价,
    "reasoning": "建议理由"
  },
  "riskFactors": ["风险因素1", "风险因素2"]
}
`;
  }

  private parseAIResponse(content: string, symbol: string, product: any): AIAnalysisResult {
    try {
      // 尝试从响应中提取JSON
      const jsonMatch = content.match(/\{[\s\S]*\}/);
      if (jsonMatch) {
        const parsed = JSON.parse(jsonMatch[0]);
        return {
          summary: parsed.summary || '',
          trend: parsed.trend || 'neutral',
          confidence: parsed.confidence || 50,
          keyFactors: parsed.keyFactors || [],
          supportLevels: parsed.supportLevels || [],
          resistanceLevels: parsed.resistanceLevels || [],
          recommendation: parsed.recommendation || { action: 'hold', reasoning: '' },
          riskFactors: parsed.riskFactors || [],
        };
      }
    } catch (error) {
      this.logger.error('解析AI响应失败:', error.message);
    }

    return this.getDefaultAnalysis(symbol);
  }

  private calculateSupportLevels(klineData: any[]): number[] {
    const lows = klineData.slice(-20).map(k => k.low);
    lows.sort((a, b) => a - b);
    return [lows[2], lows[5]].filter(Boolean);
  }

  private calculateResistanceLevels(klineData: any[]): number[] {
    const highs = klineData.slice(-20).map(k => k.high);
    highs.sort((a, b) => b - a);
    return [highs[2], highs[5]].filter(Boolean);
  }

  private generateRecommendation(
    trend: string,
    currentPrice: number,
    supports: number[],
    resistances: number[],
    confidence: number,
  ): AIAnalysisResult['recommendation'] {
    const volatility = currentPrice * 0.02;

    if (trend === 'bullish') {
      return {
        action: 'buy',
        entryPrice: currentPrice,
        stopLoss: supports[0] || currentPrice - volatility,
        targetPrice: resistances[0] || currentPrice + volatility * 2,
        reasoning: `技术分析显示多头趋势，信心指数${confidence}%。建议在支撑位附近入场，严格设置止损。`,
      };
    } else if (trend === 'bearish') {
      return {
        action: 'sell',
        entryPrice: currentPrice,
        stopLoss: resistances[0] || currentPrice + volatility,
        targetPrice: supports[0] || currentPrice - volatility * 2,
        reasoning: `技术分析显示空头趋势，信心指数${confidence}%。建议逢高做空，严格设置止损。`,
      };
    }

    return {
      action: 'hold',
      reasoning: '市场方向不明，建议观望等待更清晰的趋势信号。',
    };
  }

  private generateSummary(symbol: string, trend: string, signals: any): string {
    const trendText = trend === 'bullish' ? '偏多' : trend === 'bearish' ? '偏空' : '震荡';
    return `${symbol}当前技术面${trendText}。MACD显示${signals.macd === 'bullish' ? '金叉' : signals.macd === 'bearish' ? '死叉' : '中性'}，RSI处于${signals.rsi}区域，KDJ${signals.kdj === 'golden_cross' ? '金叉' : signals.kdj === 'dead_cross' ? '死叉' : '中性'}。`;
  }

  private generateKeyFactors(signals: any): string[] {
    const factors: string[] = [];
    if (signals.macd === 'bullish') factors.push('MACD金叉');
    if (signals.macd === 'bearish') factors.push('MACD死叉');
    if (signals.rsi === 'oversold') factors.push('RSI超卖');
    if (signals.rsi === 'overbought') factors.push('RSI超买');
    if (signals.kdj === 'golden_cross') factors.push('KDJ金叉');
    if (signals.kdj === 'dead_cross') factors.push('KDJ死叉');
    return factors.length > 0 ? factors : ['技术指标中性'];
  }

  private generateRiskFactors(trend: string, signals: any): string[] {
    const risks: string[] = ['市场系统性风险', '黑天鹅事件'];
    if (trend === 'bullish') risks.push('获利回吐压力');
    if (trend === 'bearish') risks.push('超跌反弹风险');
    if (signals.rsi === 'overbought') risks.push('技术指标超买');
    if (signals.rsi === 'oversold') risks.push('技术指标超卖');
    return risks;
  }

  private getDefaultAnalysis(symbol: string): AIAnalysisResult {
    return {
      summary: `${symbol} 数据暂时无法获取完整分析`,
      trend: 'neutral',
      confidence: 50,
      keyFactors: ['数据不足'],
      supportLevels: [],
      resistanceLevels: [],
      recommendation: {
        action: 'hold',
        reasoning: '数据不足，建议观望',
      },
      riskFactors: ['数据获取失败'],
    };
  }
}
