import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { firstValueFrom } from 'rxjs';

export interface PerplexitySearchResult {
    content: string;
    citations: string[];
}

@Injectable()
export class PerplexityService {
    private readonly logger = new Logger(PerplexityService.name);
    private readonly apiUrl = 'https://api.perplexity.ai/chat/completions';
    private readonly apiKey: string;
    private readonly isConfigured: boolean;

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

        if (!this.isConfigured) {
            this.logger.warn('Perplexity API key not configured — search enrichment will be skipped');
        }
    }

    /**
     * Search real-time bằng Perplexity Sonar
     */
    async search(query: string): Promise<PerplexitySearchResult | null> {
        if (!this.isConfigured) return null;

        try {
            const { data } = await firstValueFrom(
                this.httpService.post(
                    this.apiUrl,
                    {
                        model: 'sonar',
                        messages: [
                            {
                                role: 'system',
                                content: 'You are a helpful assistant that provides concise, factual answers about current events and trends.',
                            },
                            { role: 'user', content: query },
                        ],
                        max_tokens: 500,
                        temperature: 0.1,
                    },
                    {
                        headers: {
                            Authorization: `Bearer ${this.apiKey}`,
                            'Content-Type': 'application/json',
                        },
                    },
                ),
            );

            return {
                content: data.choices?.[0]?.message?.content || '',
                citations: data.citations || [],
            };
        } catch (error) {
            this.logger.error(`Perplexity search error: ${error.message}`);
            return null;
        }
    }

    async isAvailable(): Promise<boolean> {
        if (!this.isConfigured) return false;
        try {
            const result = await this.search('ping');
            return !!result;
        } catch {
            return false;
        }
    }
}
