import Anthropic from "@anthropic-ai/sdk";
import type { AIProvider, GenerateOptions } from "./base";
import { ConfigManager } from "../config/manager";

export class AnthropicProvider implements AIProvider {
  name = "anthropic";
  private client: Anthropic | null = null;

  private async getClient(): Promise<Anthropic> {
    if (this.client) return this.client;

    const apiKey =
      (await ConfigManager.getApiKey("anthropic")) ||
      process.env.ANTHROPIC_API_KEY;

    if (!apiKey) {
      console.error("\n❌ Anthropic API key not found");
      console.error("\nTo set your API key, use one of these methods:");
      console.error(
        "1. Set environment variable: export ANTHROPIC_API_KEY='your-key'",
      );
      console.error("2. Add to config: agi config key anthropic 'your-key'");
      console.error("\nGet your API key from: https://console.anthropic.com/");
      process.exit(1);
    }

    this.client = new Anthropic({
      apiKey: apiKey,
    });
    return this.client;
  }

  private async getModelName(): Promise<string> {
    const config = await ConfigManager.get("providers");
    return config.anthropic?.model || "claude-3-5-sonnet-20241022";
  }

  async validateConfig(): Promise<boolean> {
    try {
      const client = await this.getClient();
      const model = await this.getModelName();
      await client.messages.create({
        model,
        max_tokens: 10,
        messages: [{ role: "user", content: "test" }],
      });
      return true;
    } catch {
      return false;
    }
  }

  async generateContent(
    prompt: string,
    options?: GenerateOptions,
  ): Promise<string> {
    const client = await this.getClient();
    const defaultModel = await this.getModelName();
    const model = options?.model || defaultModel;

    const response = await client.messages.create({
      model,
      max_tokens: options?.maxTokens || 4096,
      temperature: options?.temperature || 0.7,
      messages: [{ role: "user", content: prompt }],
    });

    return response.content[0]?.type === "text" ? response.content[0].text : "";
  }
}
