<?php
require_once __DIR__ . "/db.php";
require_once __DIR__ . "/tools.php";

function smm_openai_key_from_tool(PDO $pdo, string $toolName): ?string {
  $tool = smm_tools_get_by_name($pdo, $toolName);
  if (!$tool) return null;
  $cfg = json_decode($tool["config_json"] ?? "{}", true);
  if (!is_array($cfg)) $cfg = [];
  $key = trim($cfg["api_key"] ?? "");
  return $key !== "" ? $key : null;
}

function smm_http_json(string $url, array $headers, array $payload): array {
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
  $resp = curl_exec($ch);
  $err  = curl_error($ch);
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  if ($resp === false) throw new Exception("HTTP error: ".$err);
  $data = json_decode($resp, true);
  if (json_last_error() !== JSON_ERROR_NONE) {
    throw new Exception("Non-JSON response (HTTP $code): ".$resp);
  }
  if ($code >= 400) {
    $msg = $data["error"]["message"] ?? ($data["message"] ?? "HTTP $code");
    throw new Exception("OpenAI error: ".$msg);
  }
  return $data;
}

/**
 * NOTE: These call shapes are intentionally minimal and may need adjustment
 * depending on your OpenAI API model choices.
 */
function smm_openai_generate_text(PDO $pdo, string $toolName, string $prompt): string {
  $key = smm_openai_key_from_tool($pdo, $toolName);
  if (!$key) throw new Exception("No API key set for tool: ".$toolName);

  $tool = smm_tools_get_by_name($pdo, $toolName);
  $cfg = json_decode($tool["config_json"] ?? "{}", true); if(!is_array($cfg)) $cfg=[];
  $model = $cfg["model"] ?? "gpt-4.1-mini";
  $url = $cfg["base_url"] ?? "https://api.openai.com/v1/responses";

  $payload = [
    "model"=>$model,
    "input"=>$prompt
  ];

  $data = smm_http_json($url, [
    "Authorization: Bearer ".$key,
    "Content-Type: application/json"
  ], $payload);

  // best-effort extraction
  $out = $data["output_text"] ?? "";
  if ($out === "" && isset($data["output"][0]["content"][0]["text"])) $out = $data["output"][0]["content"][0]["text"];
  return trim($out);
}

function smm_openai_generate_image_b64(PDO $pdo, string $toolName, string $prompt): string {
  $key = smm_openai_key_from_tool($pdo, $toolName);
  if (!$key) throw new Exception("No API key set for tool: ".$toolName);

  $tool = smm_tools_get_by_name($pdo, $toolName);
  $cfg = json_decode($tool["config_json"] ?? "{}", true); if(!is_array($cfg)) $cfg=[];
  $model = $cfg["model"] ?? "gpt-image-1";
  $url = $cfg["base_url"] ?? "https://api.openai.com/v1/images";

  $payload = [
    "model"=>$model,
    "prompt"=>$prompt,
    "size"=>$cfg["size"] ?? "1024x1024"
  ];

  $data = smm_http_json($url, [
    "Authorization: Bearer ".$key,
    "Content-Type: application/json"
  ], $payload);

  // best-effort extraction (varies by endpoint)
  $b64 = $data["data"][0]["b64_json"] ?? "";
  if ($b64 === "") throw new Exception("No image data returned");
  return $b64;
}


function smm_openai_tool_config(PDO $pdo, string $toolName): array {
  $tool = smm_tools_get_by_name($pdo, $toolName);
  if (!$tool) throw new Exception("Tool not found: ".$toolName);
  $cfg = json_decode($tool["config_json"] ?? "{}", true);
  if (!is_array($cfg)) $cfg = [];
  $cfg["_kind"] = $tool["kind"];
  $cfg["_enabled"] = intval($tool["is_enabled"] ?? 1);
  return $cfg;
}

function smm_openai_image_edit_b64(PDO $pdo, string $toolName, string $prompt, string $imageAbsPath): string {
  $key = smm_openai_key_from_tool($pdo, $toolName);
  if (!$key) throw new Exception("No API key set for tool: ".$toolName);

  $cfg = smm_openai_tool_config($pdo, $toolName);
  $model = $cfg["model"] ?? "gpt-image-1";
  $editsUrl = $cfg["edits_url"] ?? "https://api.openai.com/v1/images/edits";
  $size = $cfg["size"] ?? "1024x1024";

  if (!file_exists($imageAbsPath)) throw new Exception("Image file not found for edit");

  $ch = curl_init($editsUrl);
  $post = [
    "model" => $model,
    "prompt" => $prompt,
    "size" => $size,
    "image" => new CURLFile($imageAbsPath)
  ];

  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer ".$key
  ]);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

  $resp = curl_exec($ch);
  $err = curl_error($ch);
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  if ($resp === false) throw new Exception("HTTP error: ".$err);

  $data = json_decode($resp, true);
  if (json_last_error() !== JSON_ERROR_NONE) throw new Exception("Non-JSON response (HTTP $code): ".$resp);

  if ($code >= 400) {
    $msg = $data["error"]["message"] ?? ($data["message"] ?? "HTTP $code");
    throw new Exception("OpenAI error: ".$msg);
  }

  $b64 = $data["data"][0]["b64_json"] ?? "";
  if ($b64 === "") throw new Exception("No edited image returned");
  return $b64;
}

function smm_openai_create_video_job(PDO $pdo, string $toolName, string $prompt, array $opts=[]): array {
  $key = smm_openai_key_from_tool($pdo, $toolName);
  if (!$key) throw new Exception("No API key set for tool: ".$toolName);

  $cfg = smm_openai_tool_config($pdo, $toolName);
  $model = $cfg["model"] ?? "sora-2";
  $base = $cfg["base_url"] ?? "https://api.openai.com/v1/videos";

  $payload = array_merge([
    "model" => $model,
    "prompt" => $prompt,
    "duration" => $opts["duration"] ?? ($cfg["duration"] ?? 6),
    "size" => $opts["size"] ?? ($cfg["size"] ?? "1280x720")
  ], $opts);

  $data = smm_http_json($base, [
    "Authorization: Bearer ".$key,
    "Content-Type: application/json"
  ], $payload);

  return $data;
}

function smm_openai_get_video_job(PDO $pdo, string $toolName, string $videoId): array {
  $key = smm_openai_key_from_tool($pdo, $toolName);
  if (!$key) throw new Exception("No API key set for tool: ".$toolName);

  $cfg = smm_openai_tool_config($pdo, $toolName);
  $url = rtrim(($cfg["base_url"] ?? "https://api.openai.com/v1/videos"), "/") . "/" . $videoId;

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer ".$key,
    "Content-Type: application/json"
  ]);
  $resp = curl_exec($ch);
  $err = curl_error($ch);
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  if ($resp === false) throw new Exception("HTTP error: ".$err);
  $data = json_decode($resp, true);
  if (json_last_error() !== JSON_ERROR_NONE) throw new Exception("Non-JSON response (HTTP $code): ".$resp);
  if ($code >= 400) {
    $msg = $data["error"]["message"] ?? ($data["message"] ?? "HTTP $code");
    throw new Exception("OpenAI error: ".$msg);
  }
  return $data;
}

function smm_download_to_file(string $url, string $absPath): void {
  $ch = curl_init($url);
  $fp = fopen($absPath, "wb");
  if (!$fp) throw new Exception("Cannot write file: ".$absPath);

  curl_setopt($ch, CURLOPT_FILE, $fp);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 120);
  $ok = curl_exec($ch);
  $err = curl_error($ch);
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  fclose($fp);

  if ($ok === false || $code >= 400) {
    @unlink($absPath);
    throw new Exception("Download failed (HTTP $code): ".$err);
  }
}
