import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { firstValueFrom } from 'rxjs';
import {TrendItem} from "../../common/interfaces/trend-item.interface";

export interface ClaudeAnalysisResult {
    summary: string;
    category: string;
    sentiment: 'positive' | 'negative' | 'neutral';
    importance: number; // 1-10
    relatedTopics: string[];
    keyEntities: string[];
    whyTrending: string;
}

export interface ClaudeBatchAnalysisResult {
    trends: {
        title: string;
        summary: string;
        category: string;
        sentiment: 'positive' | 'negative' | 'neutral';
        score: number;
    }[];
}

@Injectable()
export class ClaudeService {
    private readonly logger = new Logger(ClaudeService.name);
    private readonly apiUrl = 'https://api.anthropic.com/v1/messages';
    private readonly apiKey: string;
    private readonly isConfigured: boolean;

    constructor(
        private readonly httpService: HttpService,
        private readonly configService: ConfigService,
    ) {
        this.apiKey = this.configService.get<string>('ai.claudeKey', '');
        this.isConfigured = !!this.apiKey;

        if (!this.isConfigured) {
            this.logger.warn(
                'Claude API key not configured — Claude analysis will be skipped',
            );
        }
    }

    /**
     * Phân tích 1 trend item chi tiết
     * Model: claude-3-5-haiku (rẻ nhất: $0.25/$1.25 per 1M tokens)
     */
    async analyzeTrend(item: TrendItem): Promise<ClaudeAnalysisResult | null> {
        if (!this.isConfigured) return null;

        try {
            const response = await this.callClaude(
                'claude-3-5-haiku-20241022',
                [
                    {
                        role: 'user',
                        content: `Analyze this trending topic and respond in JSON only:

Title: "${item.title}"
Description: "${item.description}"
Source: ${item.source}
Current engagement: ${JSON.stringify(item.engagement || {})}

Return this exact JSON format:
{
  "summary": "2-3 câu tóm tắt bằng tiếng Việt",
  "category": "tech|business|politics|entertainment|science|sports|health|other",
  "sentiment": "positive|negative|neutral",
  "importance": <1-10>,
  "relatedTopics": ["topic1", "topic2", "topic3"],
  "keyEntities": ["entity1", "entity2"],
  "whyTrending": "giải thích ngắn gọn tại sao topic này đang hot"
}`,
                    },
                ],
                300, // max_tokens — giữ nhỏ để tiết kiệm
            );

            return this.parseJsonResponse<ClaudeAnalysisResult>(response);
        } catch (error) {
            this.logger.error(`Claude analyzeTrend error: ${error.message}`);
            return null;
        }
    }

    /**
     * Phân tích BATCH nhiều trends 1 lần — TIẾT KIỆM tokens
     * Thay vì gọi 15 lần (15 × overhead), gom lại 1 lần
     */
    async analyzeBatch(
        items: TrendItem[],
    ): Promise<ClaudeBatchAnalysisResult | null> {
        if (!this.isConfigured) return null;

        const trendList = items
            .slice(0, 20)
            .map(
                (item, i) =>
                    `${i + 1}. [${item.source}] "${item.title}" — Score: ${item.score}`,
            )
            .join('\n');

        try {
            const response = await this.callClaude(
                'claude-3-5-haiku-20241022',
                [
                    {
                        role: 'user',
                        content: `Phân tích danh sách trends sau. Trả về JSON:

${trendList}

Return this exact JSON:
{
  "trends": [
    {
      "title": "tên trend",
      "summary": "tóm tắt ngắn tiếng Việt (1 câu)",
      "category": "tech|business|politics|entertainment|science|sports|health|other",
      "sentiment": "positive|negative|neutral",
      "score": <0-100, đánh giá mức độ trending>
    }
  ]
}`,
                    },
                ],
                1500,
            );

            return this.parseJsonResponse<ClaudeBatchAnalysisResult>(response);
        } catch (error) {
            this.logger.error(`Claude analyzeBatch error: ${error.message}`);
            return null;
        }
    }

    /**
     * Tóm tắt + categorize 1 nhóm trends (giống nhau) thành 1 unified trend
     */
    async summarizeGroup(
        items: TrendItem[],
    ): Promise<{ title: string; summary: string; category: string } | null> {
        if (!this.isConfigured) return null;

        const titles = items.map((i) => `- ${i.title} (${i.source})`).join('\n');

        try {
            const response = await this.callClaude(
                'claude-3-5-haiku-20241022',
                [
                    {
                        role: 'user',
                        content: `Các bài viết sau cùng 1 chủ đề. Tóm tắt thành 1 trend. JSON only:

${titles}

{
  "title": "tiêu đề tổng hợp ngắn gọn",
  "summary": "tóm tắt 2-3 câu tiếng Việt",
  "category": "tech|business|politics|entertainment|science|sports|health|other"
}`,
                    },
                ],
                250,
            );

            return this.parseJsonResponse(response);
        } catch (error) {
            this.logger.error(`Claude summarizeGroup error: ${error.message}`);
            return null;
        }
    }

    /**
     * Core API call tới Claude
     */
    private async callClaude(
        model: string,
        messages: { role: string; content: string }[],
        maxTokens: number,
    ): Promise<string> {
        const { data } = await firstValueFrom(
            this.httpService.post(
                this.apiUrl,
                {
                    model,
                    max_tokens: maxTokens,
                    temperature: 0.1, // Low temperature cho output consistent
                    messages,
                },
                {
                    headers: {
                        'x-api-key': this.apiKey,
                        'anthropic-version': '2023-06-01',
                        'Content-Type': 'application/json',
                    },
                },
            ),
        );

        const content = data.content?.[0]?.text || '';

        // Log token usage cho cost tracking
        if (data.usage) {
            this.logger.debug(
                `Claude tokens — input: ${data.usage.input_tokens}, output: ${data.usage.output_tokens}`,
            );
        }

        return content;
    }

    private parseJsonResponse<T>(content: string): T | null {
        try {
            // Extract JSON từ response (có thể wrapped trong ```json```)
            const jsonMatch = content.match(/```json\s*([\s\S]*?)```/) ||
                content.match(/(\{[\s\S]*\})/);

            if (jsonMatch) {
                return JSON.parse(jsonMatch[1] || jsonMatch[0]);
            }
            return JSON.parse(content);
        } catch (error) {
            this.logger.warn(`Failed to parse Claude JSON: ${error.message}`);
            this.logger.debug(`Raw response: ${content.substring(0, 200)}`);
            return null;
        }
    }

    /**
     * Health check — kiểm tra API key có valid không
     */
    async isAvailable(): Promise<boolean> {
        if (!this.isConfigured) return false;

        try {
            await this.callClaude(
                'claude-3-5-haiku-20241022',
                [{ role: 'user', content: 'ping' }],
                5,
            );
            return true;
        } catch {
            return false;
        }
    }
}
