<?php
declare(strict_types=1);

$base = '/home/ajenair/ajena-agent-live';
$state = $base . '/state';
$pending = $state . '/spool/pending';
$working = $state . '/spool/working';
$done = $state . '/spool/done';
$logs = $base . '/logs';
$ingestLog = $logs . '/ingest.log';
$secretFile = $state . '/processor-secret';

function log_line(string $path, string $text): void {
    @file_put_contents(
        $path,
        date('Y-m-d H:i:s') . ' ' . $text . PHP_EOL,
        FILE_APPEND | LOCK_EX
    );
}

function respond(array $data, int $status = 200): never {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(
        $data,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );
    exit;
}

foreach ([
    $base,
    $state,
    $state . '/spool',
    $pending,
    $done,
    $working,
    $state . '/spool/failed',
    $logs,
] as $dir) {
    if (!is_dir($dir)) {
        @mkdir($dir, 0700, true);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $heartbeat = $state . '/heartbeat';
    $heartbeatAge = is_file($heartbeat)
        ? max(0, time() - (int)trim((string)file_get_contents($heartbeat)))
        : null;

    respond([
        'ok' => true,
        'service' => 'AJENA AGENT INGEST',
        'heartbeat_age' => $heartbeatAge,
        'pending' => count(glob($pending . '/*.json') ?: []),
        'done' => count(glob($done . '/*.json') ?: []),
    ]);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(['ok' => false, 'error' => 'method-not-allowed'], 405);
}

$expected = is_file($secretFile)
    ? trim((string)file_get_contents($secretFile))
    : '';

$provided = $_SERVER['HTTP_X_AJENA_PROCESSOR_SECRET'] ?? '';

if (
    $expected === ''
    || $provided === ''
    || !hash_equals($expected, $provided)
) {
    log_line(
        $ingestLog,
        'FORBIDDEN expected_set=' . ($expected !== '' ? 'yes' : 'no')
        . ' provided_set=' . ($provided !== '' ? 'yes' : 'no')
    );
    respond(['ok' => false, 'error' => 'forbidden'], 403);
}

$raw = (string)file_get_contents('php://input');
$job = json_decode($raw, true);

log_line(
    $ingestLog,
    'POST received bytes=' . strlen($raw)
);

if (!is_array($job)) {
    log_line($ingestLog, 'INVALID JSON');
    respond(['ok' => false, 'error' => 'invalid-json'], 400);
}

// Authenticated health check used by Cloudflare /diagnostics.
if (($job['action'] ?? null) === 'ping') {
    log_line($ingestLog, 'AUTH PING OK');
    respond([
        'ok' => true,
        'authenticated' => true,
        'service' => 'AJENA AGENT INGEST',
        'time' => time(),
    ]);
}

// Lightweight Worker telemetry.
// This gives us Cloudflare-stage visibility directly inside cPanel logs.
if (($job['action'] ?? null) === 'worker_event') {
    $event = preg_replace(
        '/[^a-zA-Z0-9_.:-]/',
        '_',
        (string)($job['event'] ?? 'unknown')
    );

    $context = $job['context'] ?? [];
    if (!is_array($context)) {
        $context = ['value' => (string)$context];
    }

    log_line(
        $ingestLog,
        'WORKER ' . $event . ' '
        . json_encode(
            $context,
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
        )
    );

    respond([
        'ok' => true,
        'event_logged' => true,
    ]);
}

$chatId = $job['chat_id'] ?? null;
$messageId = (int)($job['message_id'] ?? 0);
$groupId = $job['media_group_id'] ?? null;

if ($chatId === null || $messageId <= 0) {
    log_line($ingestLog, 'INVALID JOB');
    respond(['ok' => false, 'error' => 'invalid-job'], 400);
}

// Durable key:
// - single track: chat_id + message_id
// - album: chat_id + media_group_id
//
// IMPORTANT FOR ALBUMS:
// Every Telegram channel_post belonging to the same media_group_id
// refreshes the SAME pending job and postpones processing for a short
// quiet period. The Agent therefore starts only AFTER Telegram has
// finished delivering the whole group.
$keyMaterial = $groupId
    ? ((string)$chatId . ':group:' . (string)$groupId)
    : ((string)$chatId . ':message:' . (string)$messageId);

$key = sha1($keyMaterial);

$pendingPath = $pending . '/' . $key . '.json';
$workingPath = $working . '/' . $key . '.json';
$donePath = $done . '/' . $key . '.json';

if (is_file($donePath)) {
    respond([
        'ok' => true,
        'accepted' => true,
        'already_done' => true,
        'job_key' => $key,
        'message_id' => $messageId,
        'media_group_id' => $groupId,
    ]);
}

// Album updates refresh the existing pending job.
// Do NOT start the group until ~2.2 seconds after the last item arrived.
if ($groupId && is_file($pendingPath)) {
    $existing = json_decode(
        (string)file_get_contents($pendingPath),
        true
    );

    if (!is_array($existing)) {
        $existing = [];
    }

    $existing = array_merge($existing, $job);
    $existing['_accepted_at'] = $existing['_accepted_at'] ?? time();
    $existing['_group_last_seen_at'] = microtime(true);
    $existing['_group_event_count'] =
        ((int)($existing['_group_event_count'] ?? 0)) + 1;
    $existing['_next_attempt_at'] = microtime(true) + 2.2;

    $tmp = $pendingPath . '.tmp.' . bin2hex(random_bytes(4));
    $encoded = json_encode(
        $existing,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );

    if (@file_put_contents($tmp, $encoded, LOCK_EX) === false) {
        @unlink($tmp);
        log_line($ingestLog, 'GROUP REFRESH WRITE FAILED key=' . $key);
        respond(['ok' => false, 'error' => 'write-failed'], 500);
    }

    @chmod($tmp, 0600);

    if (!@rename($tmp, $pendingPath)) {
        @unlink($tmp);
        log_line($ingestLog, 'GROUP REFRESH RENAME FAILED key=' . $key);
        respond(['ok' => false, 'error' => 'rename-failed'], 500);
    }

    log_line(
        $ingestLog,
        'GROUP REFRESH key=' . $key
        . ' message=' . $messageId
        . ' group=' . (string)$groupId
        . ' events=' . (string)$existing['_group_event_count']
    );

    respond([
        'ok' => true,
        'accepted' => true,
        'group_refreshed' => true,
        'job_key' => $key,
        'message_id' => $messageId,
        'media_group_id' => $groupId,
    ]);
}

// If Agent has already claimed the group, accept this webhook but do not
// create a duplicate job. Agent performs its own stable-group verification.
if ($groupId && is_file($workingPath)) {
    log_line(
        $ingestLog,
        'GROUP ALREADY WORKING key=' . $key
        . ' message=' . $messageId
        . ' group=' . (string)$groupId
    );

    respond([
        'ok' => true,
        'accepted' => true,
        'already_working' => true,
        'job_key' => $key,
        'message_id' => $messageId,
        'media_group_id' => $groupId,
    ]);
}

if (!is_file($pendingPath)) {
    $job['_accepted_at'] = time();
    $job['_attempts'] = 0;

    if ($groupId) {
        $job['_group_last_seen_at'] = microtime(true);
        $job['_group_event_count'] = 1;
        $job['_next_attempt_at'] = microtime(true) + 2.2;
    } else {
        $job['_next_attempt_at'] = 0;
    }

    $tmp = $pendingPath . '.tmp.' . bin2hex(random_bytes(4));

    $encoded = json_encode(
        $job,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );

    if (@file_put_contents($tmp, $encoded, LOCK_EX) === false) {
        @unlink($tmp);
        log_line($ingestLog, 'WRITE FAILED key=' . $key);
        respond(['ok' => false, 'error' => 'write-failed'], 500);
    }

    @chmod($tmp, 0600);

    if (!@rename($tmp, $pendingPath)) {
        @unlink($tmp);
        log_line($ingestLog, 'RENAME FAILED key=' . $key);
        respond(['ok' => false, 'error' => 'rename-failed'], 500);
    }

    log_line(
        $ingestLog,
        'ACCEPT key=' . $key
        . ' message=' . $messageId
        . ' group=' . ($groupId ?? '-')
    );
} else {
    log_line(
        $ingestLog,
        'DUPLICATE ACCEPT key=' . $key
        . ' message=' . $messageId
    );
}

respond([
    'ok' => true,
    'accepted' => true,
    'job_key' => $key,
    'message_id' => $messageId,
    'media_group_id' => $groupId,
]);
