import Anthropic from '@anthropic-ai/sdk';
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
  type IAINarrativeService,
  type NarrativeRequest,
} from '../../domain/services/ai-narrative.service';

@Injectable()
export class ClaudeNarrativeService implements IAINarrativeService {
  private readonly logger = new Logger(ClaudeNarrativeService.name);
  private readonly client: Anthropic | null;
  private readonly model = 'claude-sonnet-4-20250514';

  constructor(private readonly config: ConfigService) {
    const apiKey = this.config.get<string>('CLAUDE_API_KEY');
    this.client = apiKey ? new Anthropic({ apiKey }) : null;

    if (!this.client) {
      this.logger.warn('CLAUDE_API_KEY not configured — AI narratives will use fallback templates.');
    }
  }

  async generateNarrative(request: NarrativeRequest): Promise<string> {
    if (!this.client) {
      return this.fallbackNarrative(request);
    }

    const systemPrompt = this.buildSystemPrompt(request);
    const userPrompt = this.buildUserPrompt(request);

    try {
      const response = await this.client.messages.create({
        model: this.model,
        max_tokens: 2048,
        system: systemPrompt,
        messages: [{ role: 'user', content: userPrompt }],
      });

      const text = response.content
        .filter((block): block is Anthropic.TextBlock => block.type === 'text')
        .map((block) => block.text)
        .join('\n\n');

      return text || this.fallbackNarrative(request);
    } catch (error) {
      this.logger.error(`Claude API error for ${request.sectionKey}: ${error instanceof Error ? error.message : 'Unknown'}`);
      return this.fallbackNarrative(request);
    }
  }

  private buildSystemPrompt(request: NarrativeRequest): string {
    const locale = request.locale ?? 'vi';
    return [
      'You are an expert Vietnamese real estate market analyst.',
      `Write in ${locale === 'vi' ? 'Vietnamese' : 'English'}.`,
      'Produce concise, data-driven analysis suitable for investors and professionals.',
      'Use bullet points and short paragraphs. Include specific numbers from the provided data.',
      'Do not repeat raw JSON — interpret the data and provide actionable insights.',
      'Format output as plain text (no markdown headers).',
    ].join(' ');
  }

  private buildUserPrompt(request: NarrativeRequest): string {
    const sectionPrompts: Record<string, string> = {
      executive_summary: `Write an executive summary for a ${request.reportType} report. Highlight 3-5 key findings from the data.`,
      risk_assessment: 'Analyze investment risks based on the economic indicators and infrastructure data. Cover: market risk, regulatory risk, liquidity risk, and macro risk.',
      recommendation: 'Provide 3-5 investment recommendations with specific rationale. Include suggested strategies and risk mitigation.',
      forecast: 'Provide a 6-12 month market forecast based on macro trends, supply-demand dynamics, and infrastructure pipeline.',
      industrial_landscape: 'Analyze the industrial park landscape: occupancy trends, rental rates, key tenants, and competitive positioning.',
      market_overview: 'Provide a market overview covering transaction volume, price trends, and key drivers for the period.',
      price_analysis: 'Analyze pricing trends, distribution by segment, and identify top-performing areas.',
      supply_demand: 'Analyze supply-demand balance: new inventory, absorption rate, and days-on-market trends.',
    };

    const instruction = sectionPrompts[request.sectionKey]
      ?? `Write analysis for the "${request.sectionTitle}" section of a ${request.reportType} report.`;

    return `${instruction}\n\nData context:\n${JSON.stringify(request.context, null, 2)}`;
  }

  private fallbackNarrative(request: NarrativeRequest): string {
    return `[${request.sectionTitle}] Phân tích tự động tạm thời không khả dụng. Dữ liệu thô có sẵn trong phần dữ liệu bên dưới.`;
  }
}
