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

function smm_tools_list(PDO $pdo): array {
  $stmt = $pdo->query("SELECT * FROM tools ORDER BY updated_at DESC");
  return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function smm_tools_get(PDO $pdo, int $id): ?array {
  $stmt = $pdo->prepare("SELECT * FROM tools WHERE id=:id");
  $stmt->execute([":id"=>$id]);
  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  return $row ?: null;
}

function smm_tools_get_by_name(PDO $pdo, string $name): ?array {
  $stmt = $pdo->prepare("SELECT * FROM tools WHERE name=:n");
  $stmt->execute([":n"=>$name]);
  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  return $row ?: null;
}

function smm_tools_sanitize_name(string $name): string {
  $name = trim($name);
  if ($name === "") $name = "tool_" . date("Ymd_His") . "_" . bin2hex(random_bytes(2));
  // keep it simple
  return preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $name);
}

function smm_tools_upsert(PDO $pdo, array $t): int {
  $now = smm_now_iso();
  $name = smm_tools_sanitize_name(strval($t["name"] ?? ""));
  $kind = trim(strval($t["kind"] ?? ($t["type"] ?? ""))); if($kind==="") $kind="openai_text";
  $cfg  = $t["config"] ?? [];
  $enabled = intval($t["is_enabled"] ?? 1);

  if ($name==="" || $kind==="") throw new Exception("Tool name and kind required");
  if (!is_array($cfg)) $cfg = [];

  $json = json_encode($cfg, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

  if (!empty($t["id"])) {
    $id = intval($t["id"]);
    $stmt = $pdo->prepare("UPDATE tools SET name=:n, kind=:k, config_json=:c, is_enabled=:e, updated_at=:u WHERE id=:id");
    $stmt->execute([":n"=>$name,":k"=>$kind,":c"=>$json,":e"=>$enabled,":u"=>$now,":id"=>$id]);
    return $id;
  }

  $stmt = $pdo->prepare("INSERT INTO tools (name,kind,config_json,is_enabled,created_at,updated_at)
    VALUES (:n,:k,:c,:e,:cr,:up)");
  $stmt->execute([":n"=>$name,":k"=>$kind,":c"=>$json,":e"=>$enabled,":cr"=>$now,":up"=>$now]);
  return intval($pdo->lastInsertId());
}

function smm_tools_delete(PDO $pdo, int $id): void {
  $stmt = $pdo->prepare("DELETE FROM tools WHERE id=:id");
  $stmt->execute([":id"=>$id]);
}
