import { Injectable, Logger } from '@nestjs/common';
import { ClaudeService } from './claude.service';
import { PerplexityService } from './perplexity.service';
import {TrendItem} from "../../common/interfaces/trend-item.interface";

@Injectable()
export class AiRouterService {
    private readonly logger = new Logger(AiRouterService.name);

    constructor(
        private readonly claude: ClaudeService,
        private readonly perplexity: PerplexityService,
    ) {}

    /**
     * Placeholder — bật lên khi cần AI analysis
         * Hiện tại hệ thống chạy hoàn toàn bằng free collectors
     */
    async enrichTrends(items: TrendItem[]): Promise<TrendItem[]> {
        const claudeAvailable = await this.claude.isAvailable();
        const perplexityAvailable = await this.perplexity.isAvailable();

        if (!claudeAvailable && !perplexityAvailable) {
            this.logger.log('No AI services configured — returning raw trends');
            return items;
        }

        // Nếu Claude available → batch analyze top items
        if (claudeAvailable) {
            const topItems = items.slice(0, 20);
            const analysis = await this.claude.analyzeBatch(topItems);

            if (analysis?.trends) {
                // Merge AI analysis back vào items
                for (const aiTrend of analysis.trends) {
                    const match = items.find(
                        (item) =>
                            item.title.toLowerCase().includes(aiTrend.title.toLowerCase()) ||
                            aiTrend.title.toLowerCase().includes(item.title.toLowerCase()),
                    );
                    if (match) {
                        match.category = aiTrend.category;
                        match.description = match.description || aiTrend.summary;
                    }
                }
            }
        }

        return items;
    }
}
