import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Anthropic from '@anthropic-ai/sdk';

export interface TranslationRequest {
  type: 'FEAT' | 'ITEM' | 'SPELL' | 'ACTION' | 'SKILL' | 'CLASS' | 'ANCESTRY' | 'HERITAGE' | 'BACKGROUND' | 'CONDITION' | 'TRAIT';
  englishName: string;
  englishDescription?: string;
  englishEffect?: string; // For alchemical items with specific effect text
  context?: string;
}

export interface TranslationResponse {
  englishName: string;
  germanName: string;
  germanDescription?: string;
  germanEffect?: string; // Translated effect text
  translationQuality: 'HIGH' | 'MEDIUM' | 'LOW';
}

@Injectable()
export class ClaudeService {
  private readonly logger = new Logger(ClaudeService.name);
  private client: Anthropic;

  constructor(private configService: ConfigService) {
    const apiKey = this.configService.get<string>('ANTHROPIC_API_KEY');
    if (apiKey) {
      this.client = new Anthropic({ apiKey });
      this.logger.log('Claude API initialized');
    } else {
      this.logger.warn('ANTHROPIC_API_KEY not set - translations will be disabled');
    }
  }

  async translateBatch(items: TranslationRequest[]): Promise<TranslationResponse[]> {
    if (!this.client) {
      this.logger.warn('Claude API not available, returning untranslated items');
      return items.map(item => ({
        englishName: item.englishName,
        germanName: item.englishName,
        germanDescription: item.englishDescription,
        germanEffect: item.englishEffect,
        translationQuality: 'LOW' as const,
      }));
    }

    if (items.length === 0) {
      return [];
    }

    try {
      const itemsList = items.map((item, i) => {
        let entry = `${i + 1}. Type: ${item.type}, Name: "${item.englishName}"`;
        if (item.englishDescription) entry += `, Description: "${item.englishDescription}"`;
        if (item.englishEffect) entry += `, Effect: "${item.englishEffect}"`;
        if (item.context) entry += `, Context: ${item.context}`;
        return entry;
      }).join('\n');

      const hasEffects = items.some(i => i.englishEffect);

      const prompt = `Du bist ein Übersetzer für Pathfinder 2e Spielinhalte von Englisch nach Deutsch.

WICHTIGE ÜBERSETZUNGSREGELN:
- "Feat" = "Talent"
- "Action" = "Aktion"
- "Spell" = "Zauber"
- "Weapon" = "Waffe"
- "Armor" = "Rüstung"
- "Shield" = "Schild"
- "Item" = "Gegenstand"
- "Skill" = "Fertigkeit"
- "Class" = "Klasse"
- "Ancestry" = "Abstammung"
- "Heritage" = "Erbe"
- "Background" = "Hintergrund"
- "Condition" = "Zustand"
- "Trait" = "Merkmal"
- "persistent damage" = "andauernder Schaden"
- "splash damage" = "Splitterschaden"
- "item bonus" = "Gegenstandsbonus"
- "slashing damage" = "Hiebschaden"
- "piercing damage" = "Stichschaden"
- "bludgeoning damage" = "Wuchtschaden"
- "bleed damage" = "Blutungsschaden"
- "fire damage" = "Feuerschaden"
- "cold damage" = "Kälteschaden"
- "electricity damage" = "Elektrizitätsschaden"
- "acid damage" = "Säureschaden"
- "poison damage" = "Giftschaden"
- "mental damage" = "Geistiger Schaden"
- "sonic damage" = "Schallschaden"

STUFENBEZEICHNUNGEN (IMMER einheitlich übersetzen):
- "Lesser" = "Schwach" (z.B. "Lesser Alchemist's Fire" = "Schwaches Alchemistenfeuer")
- "Minor" = "Schwach"
- "Moderate" = "Mäßig"
- "Greater" = "Stark"
- "Major" = "Mächtig"
- "True" = "Wahr"

Behalte Pathfinder-spezifische Begriffe bei (z.B. "Versatile", "Finesse" bleiben auf Englisch als Spielmechanik-Begriffe).
Übersetze Eigennamen nicht (z.B. "Alchemist's Fire" → "Alchemistenfeuer", aber "Bane" bleibt "Bane").

Übersetze folgende ${items.length} Einträge:

${itemsList}

Antworte NUR mit einem JSON-Array in diesem Format:
[
  {
    "englishName": "Original English Name",
    "germanName": "Deutscher Name",
    "germanDescription": "Deutsche Beschreibung (falls vorhanden)"${hasEffects ? `,
    "germanEffect": "Deutscher Effekt-Text (falls vorhanden)"` : ''},
    "confidence": 0.9
  }
]

Gib confidence zwischen 0.0 und 1.0 an basierend auf der Übersetzungsqualität.`;

      const response = await this.client.messages.create({
        model: 'claude-haiku-4-5-20251001',
        max_tokens: 4000,
        messages: [{ role: 'user', content: prompt }],
      });

      const content = response.content[0];
      if (content.type !== 'text') {
        throw new Error('Unexpected response type from Claude');
      }

      // Extract JSON from response
      const jsonMatch = content.text.match(/\[[\s\S]*\]/);
      if (!jsonMatch) {
        this.logger.error('Could not extract JSON from Claude response');
        throw new Error('Invalid JSON response from Claude');
      }

      const translations = JSON.parse(jsonMatch[0]) as Array<{
        englishName: string;
        germanName: string;
        germanDescription?: string;
        germanEffect?: string;
        confidence: number;
      }>;

      return translations.map(t => ({
        englishName: t.englishName,
        germanName: t.germanName,
        germanDescription: t.germanDescription,
        germanEffect: t.germanEffect,
        translationQuality: t.confidence >= 0.8 ? 'HIGH' : t.confidence >= 0.6 ? 'MEDIUM' : 'LOW',
      }));
    } catch (error) {
      this.logger.error('Claude translation failed:', error);
      // Return untranslated items as fallback
      return items.map(item => ({
        englishName: item.englishName,
        germanName: item.englishName,
        germanDescription: item.englishDescription,
        germanEffect: item.englishEffect,
        translationQuality: 'LOW' as const,
      }));
    }
  }

  async translateSingle(item: TranslationRequest): Promise<TranslationResponse> {
    const results = await this.translateBatch([item]);
    return results[0];
  }
}
