<?php
declare(strict_types=1);

/**
 * Minimal OpenAI client for Option 2 content generation.
 */

function openai_service_url(): string {
  return 'https://api.openai.com/v1/chat/completions';
}

function openai_request(string $apiKey, array $payload): array {
  $ch = curl_init(openai_service_url());
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
      'Content-Type: application/json',
      'Authorization: Bearer ' . $apiKey,
    ],
    CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_SLASHES),
    CURLOPT_TIMEOUT => 25,
  ]);
  $body = curl_exec($ch);
  $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $error = curl_error($ch);
  curl_close($ch);

  if ($body === false) {
    return ['ok' => false, 'status' => $status, 'body' => '', 'error' => $error ?: 'curl_failed'];
  }
  return ['ok' => true, 'status' => $status, 'body' => (string)$body, 'error' => ''];
}

function openai_extract_choice(array $decoded): ?string {
  if (!isset($decoded['choices']) || !is_array($decoded['choices'])) {
    return null;
  }
  $choice = $decoded['choices'][0] ?? null;
  if (!is_array($choice)) return null;
  $message = $choice['message'] ?? [];
  if (!is_array($message)) return null;
  return (string)($message['content'] ?? '');
}

function openai_parse_json_output(string $content): ?array {
  $trimmed = trim($content);
  $decoded = json_decode($trimmed, true);
  if (is_array($decoded)) {
    return $decoded;
  }

  $start = strpos($trimmed, '{');
  $end = strrpos($trimmed, '}');
  if ($start === false || $end === false || $end <= $start) return null;
  $json = substr($trimmed, $start, $end - $start + 1);
  $decoded = json_decode($json, true);
  return is_array($decoded) ? $decoded : null;
}

function openai_simple_test_payload(): array {
  return [
    'model' => 'gpt-3.5-turbo',
    'messages' => [
      ['role' => 'system', 'content' => 'You are a reliable assistant. Reply with the word ok.'],
      ['role' => 'user', 'content' => 'Return ok.'],
    ],
    'max_tokens' => 1,
    'temperature' => 0,
    'n' => 1,
  ];
}

function openai_generation_payload(string $subject, string $titleOverride, string $ref): array {
  $titleHint = $titleOverride !== '' ? $titleOverride : $subject;
  $content = <<<PROMPT
You are MY.TOWN Blogger's content assistant. Generate a short blog article for the tenant {$ref} covering the topic "{$subject}".
Return a JSON object only (no surrounding text) with these properties:
- "title": a compelling headline inspired by "{$titleHint}".
- "html": the article body in HTML. Keep it friendly, simple, and wrapped in tags like <article> or <section>.
- "plaintext_excerpt": a plain-text summary under 200 characters.
- "social_snippets": an object with "caption_short", "caption_long", and "hashtags" (array of strings, each starting with #).
Make sure the JSON is valid.
PROMPT;

  return [
    'model' => 'gpt-3.5-turbo',
    'messages' => [
      ['role' => 'system', 'content' => 'You are MY.TOWN Blogger content assistant.'],
      ['role' => 'user', 'content' => $content],
    ],
    'temperature' => 0.5,
    'max_tokens' => 512,
    'top_p' => 1,
    'n' => 1,
  ];
}
