<?php
/*
 * gemini-proxy.example.php — EXAMPLE ONLY. Disabled by default. Not used by DiscoveryVIP.
 * Purpose: let a public web page call Gemini WITHOUT exposing an API key.
 * The key is read from a server environment variable; it is never sent to the browser.
 * Before enabling: put it behind authentication, set GEMINI_API_KEY in the server
 * environment, review the limits, tell users what is sent, and get their consent.
 */
const ENABLED = false;                       // must be switched on deliberately
const ALLOWED_MODELS = ['gemini-2.5-flash']; // allow-list: confirm current names in the official docs
const MAX_PROMPT = 8000;                     // characters
const MAX_PER_HOUR = 30;                     // per client IP

header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');
if (!ENABLED) { http_response_code(503); echo json_encode(['error' => 'Live Gemini is disabled on this site.']); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }
$key = getenv('GEMINI_API_KEY');
if (!$key) { http_response_code(500); echo json_encode(['error' => 'Server not configured.']); exit; }

// Simple per-IP rate limit (file based; use a real store in production).
$bucket = sys_get_temp_dir() . '/gproxy_' . md5($_SERVER['REMOTE_ADDR'] ?? 'x') . '_' . date('YmdH');
$count = (int) @file_get_contents($bucket);
if ($count >= MAX_PER_HOUR) { http_response_code(429); echo json_encode(['error' => 'Rate limit reached. Try later.']); exit; }
file_put_contents($bucket, $count + 1);

$in = json_decode(file_get_contents('php://input'), true);
$prompt = is_array($in) ? (string) ($in['prompt'] ?? '') : '';
$model = is_array($in) ? (string) ($in['model'] ?? ALLOWED_MODELS[0]) : ALLOWED_MODELS[0];
if ($prompt === '' || strlen($prompt) > MAX_PROMPT) { http_response_code(400); echo json_encode(['error' => 'Prompt missing or too long.']); exit; }
if (!in_array($model, ALLOWED_MODELS, true)) { http_response_code(400); echo json_encode(['error' => 'Model not allowed.']); exit; }

$body = json_encode(['contents' => [['parts' => [['text' => $prompt]]]], 'generationConfig' => ['responseMimeType' => 'application/json']]);
$ch = curl_init('https://generativelanguage.googleapis.com/v1beta/models/' . rawurlencode($model) . ':generateContent');
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'x-goog-api-key: ' . $key]]);
$res = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE) ?: 502;
curl_close($ch);
http_response_code($code);
// Return only the model text and status; never echo headers or the key.
$j = json_decode($res ?: '{}', true);
echo json_encode(['status' => $code, 'text' => $j['candidates'][0]['content']['parts'][0]['text'] ?? null, 'error' => $j['error']['message'] ?? null, 'source' => 'live Gemini via server proxy']);
