<?php

require_once dirname(__DIR__) . '/db_bootstrap.php';
require_once dirname(__DIR__) . '/app_runtime.php';
require_once dirname(__DIR__) . '/install_link_lib.php';

$conn = ensure_db(true);
$action = $argv[1] ?? '';
$instanceId = 'acceptance_agent_install_20260619';
$secret = 'acceptance-agent-install-secret';
$secretHash = hash('sha256', $secret);
$agentId = 25;

if ($action === 'enable') {
  ua_link_ensure_schema($conn);
  $instanceEsc = $conn->real_escape_string($instanceId);
  $hashEsc = $conn->real_escape_string($secretHash);
  @$conn->query("INSERT INTO ua_link_requests (instance_id,instance_name,install_type,request_secret_hash,status,approved_at,created_at,updated_at)
    VALUES ('{$instanceEsc}','Acceptance Agent Install','agent','{$hashEsc}','approved',NOW(),NOW(),NOW())
    ON DUPLICATE KEY UPDATE request_secret_hash=VALUES(request_secret_hash),status='approved',approved_at=NOW(),updated_at=NOW()");
  if (!$conn->query("UPDATE agents SET linked_instance_id='{$instanceEsc}' WHERE id={$agentId}")) {
    fwrite(STDERR, $conn->error . PHP_EOL);
    exit(1);
  }
  $config = ua_install_config();
  $config['install_type'] = 'agent';
  $config['link'] = [
    'status'=>'approved',
    'instance_id'=>$instanceId,
    'secret'=>$secret,
    'server_url'=>(string)($config['server_url'] ?? 'http://127.0.0.1:8080/'),
  ];
  $error = '';
  if (!ua_save_install_config($config, $error)) {
    fwrite(STDERR, $error . PHP_EOL);
    exit(1);
  }
  echo json_encode(['ok'=>true,'mode'=>'agent','instance_id'=>$instanceId,'agent_id'=>$agentId], JSON_UNESCAPED_UNICODE) . PHP_EOL;
  exit;
}

if ($action === 'restore') {
  $instanceEsc = $conn->real_escape_string($instanceId);
  @$conn->query("UPDATE agents SET linked_instance_id=NULL WHERE id={$agentId} AND linked_instance_id='{$instanceEsc}'");
  @$conn->query("DELETE FROM ua_link_requests WHERE instance_id='{$instanceEsc}'");
  @$conn->query("DELETE FROM agent_sync_nonces WHERE instance_id='{$instanceEsc}'");
  $config = ua_install_config();
  $config['install_type'] = 'server';
  $config['link'] = ['status'=>'unlinked','instance_id'=>'','secret'=>'','server_url'=>(string)($config['server_url'] ?? '')];
  $error = '';
  if (!ua_save_install_config($config, $error)) {
    fwrite(STDERR, $error . PHP_EOL);
    exit(1);
  }
  echo json_encode(['ok'=>true,'mode'=>'server','restored'=>true], JSON_UNESCAPED_UNICODE) . PHP_EOL;
  exit;
}

fwrite(STDERR, "Use enable or restore.\n");
exit(1);
