<?php
declare(strict_types=1);

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

$cfg = require __DIR__ . '/../config.php';
require_once __DIR__ . '/../lib/content_drafts.php';
require_once __DIR__ . '/../lib/wp_common.php';
require_once __DIR__ . '/../lib/mail_helper.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;
}

function content_api_base_url(): string {
  $raw = $_ENV['BLOGGER_API_BASE_URL'] ?? getenv('BLOGGER_API_BASE_URL') ?? '';
  if ($raw === '') {
    $raw = 'https://api.blogger.mytown.ink';
  }
  return rtrim($raw, '/');
}

function content_sanitize_hashtags(array $input): array {
  $out = [];
  foreach ($input as $value) {
    $tag = trim((string)$value);
    if ($tag === '') continue;
    if (!str_starts_with($tag, '#')) $tag = '#' . $tag;
    $tag = preg_replace('/[^#\p{L}\p{N}]+/u', '', $tag);
    if ($tag === '#' || $tag === '') continue;
    $tag = strtolower($tag);
    if (!in_array($tag, $out, true)) {
      $out[] = $tag;
    }
    if (count($out) >= 8) break;
  }
  return array_values($out);
}

$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'] ?? ''));
$topic = trim((string)($body['topic'] ?? ''));
$prompt = trim((string)($body['prompt'] ?? ''));
$titleInput = trim((string)($body['title'] ?? ''));

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

$subject = $topic !== '' ? $topic : $prompt;
if ($subject === '') {
  respond(400, ['ok' => false, 'error' => 'topic or prompt required']);
}

$paths = tenant_paths($cfg, $ref);
$active = content_read_json($paths['active']);
if (!is_array($active) || strtolower((string)($active['status'] ?? '')) !== 'active') {
  respond(400, ['ok' => false, 'error' => 'Tenant not active']);
}

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

if ($openaiKey === null) {
  respond(400, ['ok' => false, 'error' => 'OpenAI key not configured for tenant']);
}

$payload = openai_generation_payload($subject, $titleInput, $ref);
$result = openai_request($openaiKey, $payload);

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

if ($result['status'] >= 400) {
  $decoded = json_decode($result['body'], true);
  $err = is_array($decoded) && isset($decoded['error']['message']) ? $decoded['error']['message'] : 'OpenAI request rejected';
  respond(502, ['ok' => false, 'error' => $err, 'http_code' => $result['status']]);
}

$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]);
}

$content = openai_extract_choice($decoded);
if ($content === null) {
  respond(502, ['ok' => false, 'error' => 'OpenAI response missing content']);
}

$structured = openai_parse_json_output($content);
if (!is_array($structured)) {
  respond(502, ['ok' => false, 'error' => 'Unable to parse OpenAI JSON output']);
}

$title = $titleInput !== '' ? $titleInput : trim((string)($structured['title'] ?? ''));
if ($title === '') {
  respond(502, ['ok' => false, 'error' => 'OpenAI output missing title']);
}

$html = trim((string)($structured['html'] ?? ''));
if ($html === '') {
  respond(502, ['ok' => false, 'error' => 'OpenAI output missing html']);
}

$plain = trim((string)($structured['plaintext_excerpt'] ?? ''));
if ($plain === '') {
  $plain = trim(strip_tags($html));
}
if ($plain === '') {
  $plain = 'Preview this draft in the generated HTML.';
}

$socialRaw = is_array($structured['social_snippets'] ?? null) ? $structured['social_snippets'] : [];
$captionShort = trim((string)($socialRaw['caption_short'] ?? ''));
$captionLong = trim((string)($socialRaw['caption_long'] ?? ''));
$hashtags = content_sanitize_hashtags(is_array($socialRaw['hashtags'] ?? null) ? $socialRaw['hashtags'] : []);
if (empty($hashtags)) {
  $hashtags = ['#mytown', '#blogger'];
}

$generatedAt = date('c');
$snippets = [
  'caption_short' => $captionShort !== '' ? $captionShort : "Review this draft for {$subject}.",
  'caption_long' => $captionLong !== '' ? $captionLong : "Review this draft for {$subject} before publishing to your WordPress site.",
  'hashtags' => $hashtags,
];

$draftId = content_generate_draft_id();
while (file_exists(content_draft_path($cfg, $ref, $draftId))) {
  $draftId = content_generate_draft_id();
}

$previewToken = content_generate_token();
$approveToken = content_generate_token();

$now = time();
$previewTtl = (int)($cfg['preview_token_ttl_secs'] ?? 604800);
if ($previewTtl <= 0) {
  $previewTtl = 604800;
}
$approveTtl = (int)($cfg['approve_token_ttl_secs'] ?? 604800);
if ($approveTtl <= 0) {
  $approveTtl = 604800;
}

$draft = [
  'draft_id' => $draftId,
  'title' => $title,
  'html' => $html,
  'plaintext_excerpt' => $plain,
  'created_at' => $generatedAt,
  'status' => 'generated',
  'social_snippets' => $snippets,
  'preview_token' => $previewToken,
  'preview_expires_at' => gmdate('c', $now + $previewTtl),
  'approve_token' => $approveToken,
  'approve_expires_at' => gmdate('c', $now + $approveTtl),
];

if (!content_save_draft($cfg, $ref, $draftId, $draft)) {
  respond(500, ['ok' => false, 'error' => 'Failed to store draft']);
}

$baseUrl = content_api_base_url();
$previewUrl = $baseUrl . $draft['preview_path'];
$approveUrl = $baseUrl . $draft['approve_path'];

$emailStatus = 'skipped_missing_email';
$emailError = 'Tenant email missing';
$tenantEmail = trim((string)($active['email'] ?? ''));

if ($tenantEmail !== '') {
  if (!mail_is_configured()) {
    $emailStatus = 'skipped_missing_smtp';
    $emailError = 'SMTP configuration incomplete';
  } else {
    $subjectLine = "MY.TOWN Blogger draft ready (ref {$ref} / {$draftId})";
    $curl = "curl -X POST \"{$approveUrl}\" -H 'Content-Type: application/json' -d '{\"ref\":\"{$ref}\",\"draft\":\"{$draftId}\",\"token\":\"{$approveToken}\"}'";
    $bodyText = <<<TXT
Hello,

Tenant ref: {$ref}
Draft ID: {$draftId}

Preview link:
{$previewUrl}

Approve endpoint:
{$approveUrl}
Approve token: {$approveToken}

Instructions:
1. Click or paste the preview link to review the HTML preview and social snippets.
2. When ready to publish, POST to the approve endpoint with the JSON payload shown below; the stored WordPress credentials handle the publish and return the canonical link.

{$curl}

Best,
MY.TOWN Blogger
TXT;

    $resultMail = mail_send_message($tenantEmail, $subjectLine, $bodyText);
    if ($resultMail['sent']) {
      $emailStatus = 'sent';
      $emailError = '';
    } else {
      $emailStatus = 'failed';
      $emailError = $resultMail['error'] ?: 'Unknown SMTP error';
      error_log("Draft email failed for {$ref}/{$draftId}: {$emailError}");
    }
  }
}

respond(201, [
  'ok' => true,
  'draft_id' => $draftId,
  'status' => $draft['status'],
  'preview_token' => $previewToken,
  'approve_token' => $approveToken,
  'preview_path' => "/content/preview.php?ref={$ref}&draft={$draftId}&token={$previewToken}",
  'preview_url' => $previewUrl,
  'approve_path' => "/content/approve.php",
  'approve_url' => $approveUrl,
  'email_status' => $emailStatus,
  'email_error' => $emailError,
]);
