<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

$cfg = require __DIR__ . '/../config.php';
require_once __DIR__ . '/../lib/openai_store.php';
require_once __DIR__ . '/../lib/openai_client.php';

function respond(int $code, array $payload): never {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}

$raw = file_get_contents('php://input') ?: '';
$body = $raw === '' ? [] : json_decode($raw, true);
if (!is_array($body)) {
  respond(400, ['ok' => false, 'error' => 'Invalid JSON']);
}

$ref = trim((string)($body['ref'] ?? ''));
if ($ref === '' || !preg_match('/^t_[a-f0-9]{16}$/', $ref)) {
  respond(400, ['ok' => false, 'error' => 'Invalid tenant_ref']);
}

try {
  $key = openai_load_key($cfg, $ref);
} catch (Throwable $e) {
  respond(500, ['ok' => false, 'error' => 'OpenAI master key missing', 'details' => $e->getMessage()]);
}
if ($key === null) {
  respond(400, ['ok' => false, 'error' => 'OpenAI key not configured']);
}

$payload = openai_simple_test_payload();
$result = openai_request($key, $payload);
if (!$result['ok']) {
  respond(502, ['ok' => false, 'error' => $result['error']]);
}

$decoded = json_decode($result['body'], true);
if (!is_array($decoded)) {
  respond(502, ['ok' => false, 'error' => 'Invalid OpenAI response']);
}

if (isset($decoded['error'])) {
  $err = $decoded['error']['message'] ?? 'OpenAI error';
  respond($result['status'], ['ok' => false, 'error' => $err]);
}

$message = trim((string)(openai_extract_choice($decoded) ?? ''));
respond(200, ['ok' => true, 'message' => $message !== '' ? $message : 'ok']);
