<?php
// socialmediamanager/api/router_run.php
require_once __DIR__ . "/../app/db.php";
require_once __DIR__ . "/../app/openai.php";
require_once __DIR__ . "/../app/tagx.php";

try {
  $pdo = smm_db();
  $b = smm_read_json_body();
  $text = trim($b["text"] ?? "");
  if ($text==="") smm_json_response(["ok"=>false,"error"=>"text required"],400);

  // Rule-based routing by default
  $route = "writer";
  $lc = strtolower($text);
  if (strpos($lc, "tag") !== false || strpos($lc, "meta") !== false || strpos($lc, "seo") !== false) $route = "seo";
  if (strpos($lc, "publish") !== false || strpos($lc, "schedule") !== false) $route = "publisher";

  // If OpenAI enabled, let it choose among known agents
  if (smm_openai_enabled()) {
    $agents = $pdo->query("SELECT key,name,description,preferred_tool_key FROM agents")->fetchAll(PDO::FETCH_ASSOC);
    $agentList = json_encode($agents, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

    $sys = "You are a router that chooses the best agent key for the user's request. Output only JSON: {"agent_key":"...","reason":"..."}.";
    $usr = "User request: {$text}\nAvailable agents: {$agentList}";
    $resp = smm_openai_chat([["role"=>"system","content"=>$sys],["role"=>"user","content"=>$usr]],["temperature"=>0.1]);
    $raw = $resp["choices"][0]["message"]["content"] ?? "";
    $dec = json_decode($raw, true);
    if (is_array($dec) && isset($dec["agent_key"])) $route = $dec["agent_key"];
  }

  $output = ["route"=>$route,"note"=>"Phase 3 router demo. Use Draft Generator / TagX / Publisher tabs for full features."];

  $pdo->prepare("INSERT INTO runs (route,input_json,output_json,created_at) VALUES (:r,:i,:o,:c)")
      ->execute([":r"=>$route,":i"=>json_encode(["text"=>$text]),":o"=>json_encode($output),":c"=>smm_now_iso()]);

  smm_json_response(["ok"=>true,"result"=>$output]);

} catch(Throwable $e) {
  smm_log("router_run error: ".$e->getMessage(),"ERROR");
  smm_json_response(["ok"=>false,"error"=>$e->getMessage()],500);
}
