<?php
/**
 * anthropic-proxy.php
 * -----------------------------------------------------------------
 * Server-side proxy for the Clyde 37-DE / RCI-1550 dashboard's AI
 * Troubleshooting Assistant, to be hosted on cPanel alongside the
 * dashboard HTML file. Same pattern as groq-proxy.php, just pointed
 * at Anthropic's API instead.
 *
 * Why this exists: your Anthropic API key must NEVER be exposed in
 * browser JavaScript. This script keeps the key on the server and
 * forwards the chat request to Anthropic, then relays the response.
 *
 * SETUP ON CPANEL
 * 1. Upload this file to the SAME folder as the dashboard HTML and
 *    groq-proxy.php (e.g. public_html/clyde37de.offshoreai.online/).
 * 2. Get an Anthropic API key at https://console.anthropic.com
 *    (Settings -> API Keys). This is separate from a claude.ai login.
 * 3. Put the key in a file OUTSIDE public_html — see ANTHROPIC_SECRET_PATH
 *    below, same approach as groq-secret.php.
 * 4. In the dashboard HTML, set AI_BACKEND = 'anthropic-proxy'.
 * -----------------------------------------------------------------
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');      // tighten to your own domain once live
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

/* ---------------------------------------------------------------
 * METHOD A (recommended): key stored in a file OUTSIDE any
 * web-accessible folder, directly in your cPanel account's home
 * directory — same placement rule as groq-secret.php:
 *   /home/caracuanbiz/anthropic-secret.php
 * containing only:
 *   <?php return 'sk-ant-xxxxxxxxxxxxxxxxxxxxx';
 * ------------------------------------------------------------- */
define('ANTHROPIC_SECRET_PATH', '/home/caracuanbiz/anthropic-secret.php');
$apiKey = is_file(ANTHROPIC_SECRET_PATH) ? include ANTHROPIC_SECRET_PATH : null;

/* ---------------------------------------------------------------
 * METHOD B (quick start, less safe): paste your key directly below.
 * ------------------------------------------------------------- */
if (!$apiKey) {
    $apiKey = ''; // <-- paste your Anthropic key here as a fallback, e.g. 'sk-ant-...'
}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Visit this file's URL directly in a browser to sanity-check deployment.
    echo json_encode([
        'status' => 'anthropic-proxy.php is reachable',
        'php_version' => phpversion(),
        'curl_available' => function_exists('curl_init'),
        'secret_file_path' => ANTHROPIC_SECRET_PATH,
        'secret_file_found' => is_file(ANTHROPIC_SECRET_PATH),
        'api_key_loaded' => !empty($apiKey),
        'note' => 'This GET response is just a diagnostic check. The dashboard itself sends a POST request.',
    ]);
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed. Use POST.']);
    exit;
}

if (!$apiKey) {
    http_response_code(500);
    echo json_encode(['error' => 'Server is missing an Anthropic API key. See setup notes in anthropic-proxy.php.']);
    exit;
}

$incoming = file_get_contents('php://input');
$payload = json_decode($incoming, true);

if (!is_array($payload) || empty($payload['messages'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Request body must include a "messages" array.']);
    exit;
}

// Force sane defaults if the client didn't set them.
if (empty($payload['model'])) {
    $payload['model'] = 'claude-sonnet-4-6';
}
if (empty($payload['max_tokens'])) {
    $payload['max_tokens'] = 1000;
}

$ch = curl_init('https://api.anthropic.com/v1/messages');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($payload),
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'x-api-key: ' . $apiKey,
        'anthropic-version: 2023-06-01',
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr  = curl_error($ch);
curl_close($ch);

if ($response === false) {
    http_response_code(502);
    echo json_encode(['error' => 'Could not reach Anthropic: ' . $curlErr]);
    exit;
}

http_response_code($httpCode ?: 502);
echo $response;