/**
 * Claude (Anthropic) Integration
 * ---------------------------------
 * Auth: API key (ANTHROPIC_API_KEY)
 * API: https://api.anthropic.com/v1
 *
 * This integration verifies that the Anthropic API key works
 * and enables the AI Avatar to use real Claude responses.
 */

import type { IntegrationCredentials } from "@/lib/services/integration-credentials";
import { SyncService, SyncResult } from "./types";

export const claude: SyncService = {
  id: "claude",
  name: "Claude (Anthropic)",

  async connect(brandId: string, creds?: IntegrationCredentials): Promise<SyncResult> {
    const apiKey = creds?.apiKey || process.env.ANTHROPIC_API_KEY;
    if (!apiKey) {
      return { success: false, message: "Anthropic API key is required. Set ANTHROPIC_API_KEY in your environment or provide it here." };
    }

    // Verify the key works with a minimal API call
    try {
      const res = await fetch("https://api.anthropic.com/v1/messages", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-api-key": apiKey,
          "anthropic-version": "2023-06-01",
        },
        body: JSON.stringify({
          model: "claude-sonnet-4-20250514",
          max_tokens: 10,
          messages: [{ role: "user", content: "ping" }],
        }),
      });

      if (!res.ok) {
        const err = await res.text();
        return { success: false, message: `Anthropic key verification failed: ${err}` };
      }

      return {
        success: true,
        message: "Claude (Anthropic) connected — AI Avatar is live.",
        credentials: { apiKey },
      };
    } catch (err) {
      return { success: false, message: `Connection error: ${err instanceof Error ? err.message : "Unknown"}` };
    }
  },

  async disconnect(): Promise<SyncResult> {
    return { success: true, message: "Claude disconnected. AI Avatar will use mock responses." };
  },

  async sync(): Promise<SyncResult> {
    // Claude doesn't "sync" data — it's an on-demand API
    const apiKey = process.env.ANTHROPIC_API_KEY;
    return {
      success: !!apiKey,
      message: apiKey ? "Claude API key is active." : "No Anthropic API key configured.",
    };
  },
};
