<?php
declare(strict_types=1);

require_once __DIR__ . '/wp_common.php';

function content_read_json(string $path): ?array {
  if (!is_file($path)) return null;
  $raw = file_get_contents($path);
  if ($raw === false) return null;
  $data = json_decode($raw, true);
  return is_array($data) ? $data : null;
}

function content_write_json_atomic(string $path, array $data, int $mode = 0640): bool {
  $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
  if ($json === false) return false;
  $tmp = $path . '.tmp';
  if (file_put_contents($tmp, $json, LOCK_EX) === false) return false;
  @chmod($tmp, $mode);
  if (!@rename($tmp, $path)) {
    @unlink($tmp);
    return false;
  }
  return true;
}

function content_generate_token(int $bytes = 24): string {
  return bin2hex(random_bytes($bytes));
}

function content_generate_draft_id(): string {
  return 'd_' . bin2hex(random_bytes(12));
}

function content_drafts_base_dir(array $cfg, string $ref): string {
  $paths = tenant_paths($cfg, $ref);
  return rtrim($paths['tenantDir'], '/') . '/drafts';
}

function content_drafts_dir(array $cfg, string $ref): string {
  $dir = content_drafts_base_dir($cfg, $ref);
  if (is_dir($dir)) return $dir;
  if (!@mkdir($dir, 0750, true) && !is_dir($dir)) {
    throw new RuntimeException('Failed to create drafts directory');
  }
  @chmod($dir, 0750);
  return $dir;
}

function content_draft_path(array $cfg, string $ref, string $draftId): string {
  $dir = content_drafts_dir($cfg, $ref);
  return $dir . '/' . $draftId . '.json';
}

function content_read_draft(array $cfg, string $ref, string $draftId): ?array {
  $base = content_drafts_base_dir($cfg, $ref);
  $path = $base . '/' . $draftId . '.json';
  return content_read_json($path);
}

function content_save_draft(array $cfg, string $ref, string $draftId, array $draft): bool {
  $path = content_draft_path($cfg, $ref, $draftId);
  return content_write_json_atomic($path, $draft);
}
