<?php

declare(strict_types=1);

ignore_user_abort(true);

@set_time_limit(600);

header(
    'Content-Type: application/json; charset=utf-8'
);


function respond(
    array $data,
    int $status = 200
): void {

    http_response_code(
        $status
    );

    echo json_encode(
        $data,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES
    );

    exit;
}


function extractJsonResult(
    array $lines
): ?array {

    for (
        $i = count($lines) - 1;
        $i >= 0;
        $i--
    ) {

        $line =
            trim(
                (string)
                $lines[$i]
            );

        if ($line === '') {
            continue;
        }

        $decoded =
            json_decode(
                $line,
                true
            );

        if (
            is_array(
                $decoded
            )
        ) {
            return $decoded;
        }
    }

    return null;
}


/*
|--------------------------------------------------------------------------
| Config
|--------------------------------------------------------------------------
*/

$configPath =
    dirname(__DIR__, 2)
    . '/ajena_config.php';


if (
    !is_file(
        $configPath
    )
) {

    respond(
        [
            'ok' => false,

            'error' =>
                'AJENA config not found'
        ],
        500
    );
}


$config =
    require $configPath;


/*
|--------------------------------------------------------------------------
| Health
|--------------------------------------------------------------------------
*/

if (
    ($_SERVER[
        'REQUEST_METHOD'
    ] ?? '')
    !== 'POST'
) {

    respond([
        'ok' => true,

        'service' =>
            'AJENA Demo Processor',

        'status' =>
            'online',

        'engine' =>
            'cloudflare-queue-mtproto',

        'background_spawn' =>
            false,
    ]);
}


/*
|--------------------------------------------------------------------------
| Authenticate Cloudflare
|--------------------------------------------------------------------------
*/

$receivedSecret =
    (string) (
        $_SERVER[
            'HTTP_X_AJENA_PROCESSOR_SECRET'
        ]
        ?? ''
    );


$expectedSecret =
    (string) (
        $config[
            'processor_secret'
        ]
        ?? ''
    );


if (
    $expectedSecret === ''
    ||
    !hash_equals(
        $expectedSecret,
        $receivedSecret
    )
) {

    respond(
        [
            'ok' => false,
            'error' =>
                'Forbidden'
        ],
        403
    );
}


/*
|--------------------------------------------------------------------------
| Parse Queue job
|--------------------------------------------------------------------------
*/

$raw =
    file_get_contents(
        'php://input'
    );


if (
    $raw === false
    ||
    trim($raw) === ''
) {

    respond(
        [
            'ok' => false,
            'error' =>
                'Empty request'
        ],
        400
    );
}


$job =
    json_decode(
        $raw,
        true
    );


if (
    !is_array(
        $job
    )
) {

    respond(
        [
            'ok' => false,
            'error' =>
                'Invalid JSON'
        ],
        400
    );
}


$chatId =
    $job[
        'chat_id'
    ]
    ?? null;


$messageId =
    (int) (
        $job[
            'message_id'
        ]
        ?? 0
    );


if (
    !$chatId
    ||
    $messageId <= 0
) {

    respond(
        [
            'ok' => false,

            'error' =>
                'Missing job data'
        ],
        400
    );
}


/*
|--------------------------------------------------------------------------
| Paths
|--------------------------------------------------------------------------
*/

$processorDir =
    '/home/ajenair/ajena_processor';


$jobDir =
    $processorDir
    . '/jobs';


$doneDir =
    $processorDir
    . '/done';


$python =
    $processorDir
    . '/venv/bin/python';


$script =
    $processorDir
    . '/processor.py';


$stderrLog =
    $processorDir
    . '/processor.stderr.log';


$runtimeLockPath =
    $processorDir
    . '/processor-runtime.lock';


foreach (
    [
        $processorDir,
        $jobDir,
        $doneDir
    ]
    as $dir
) {

    if (
        !is_dir(
            $dir
        )
    ) {

        @mkdir(
            $dir,
            0700,
            true
        );
    }
}


if (
    !is_file($python)
    ||
    !is_file($script)
) {

    respond(
        [
            'ok' => false,

            'error' =>
                'Python processor is not installed'
        ],
        500
    );
}


/*
|--------------------------------------------------------------------------
| Idempotency
|--------------------------------------------------------------------------
|
| VERY IMPORTANT:
|
| We ONLY use:
|
| chat_id + message_id
|
| We DO NOT use:
|
| file_id
| file_unique_id
| filename
| title
| performer
| audio hash
|
| Therefore:
|
| Telegram retries same update:
| → no duplicate demo
|
| User posts SAME SONG again:
| → new message_id
| → NEW DEMO
|
*/

$idempotencyKey =
    hash(
        'sha256',

        (string)
        $chatId

        . ':'

        . $messageId
    );


$doneFile =
    $doneDir
    . '/'
    . $idempotencyKey
    . '.json';


if (
    is_file(
        $doneFile
    )
) {

    $saved =
        json_decode(
            (string)
            @file_get_contents(
                $doneFile
            ),
            true
        );


    respond([
        'ok' => true,

        'demo' =>
            'already-done',

        'message_id' =>
            $messageId,

        'previous_result' =>
            is_array($saved)
                ? $saved
                : null,
    ]);
}


/*
|--------------------------------------------------------------------------
| Global processor lock
|--------------------------------------------------------------------------
|
| Even if Queue concurrency is accidentally
| configured above 1, only one MTProto processor
| can execute at a time.
|
*/

$runtimeLock =
    fopen(
        $runtimeLockPath,
        'c'
    );


if (
    !$runtimeLock
) {

    respond(
        [
            'ok' => false,

            'error' =>
                'Cannot open processor runtime lock'
        ],
        500
    );
}


if (
    !flock(
        $runtimeLock,
        LOCK_EX
    )
) {

    fclose(
        $runtimeLock
    );


    respond(
        [
            'ok' => false,

            'error' =>
                'Cannot acquire processor runtime lock'
        ],
        500
    );
}


/*
|--------------------------------------------------------------------------
| Re-check after lock
|--------------------------------------------------------------------------
*/

if (
    is_file(
        $doneFile
    )
) {

    flock(
        $runtimeLock,
        LOCK_UN
    );

    fclose(
        $runtimeLock
    );


    respond([
        'ok' => true,

        'demo' =>
            'already-done',

        'message_id' =>
            $messageId,
    ]);
}


/*
|--------------------------------------------------------------------------
| Job file
|--------------------------------------------------------------------------
*/

try {

    $random =
        bin2hex(
            random_bytes(8)
        );

} catch (
    Throwable $e
) {

    flock(
        $runtimeLock,
        LOCK_UN
    );

    fclose(
        $runtimeLock
    );


    respond(
        [
            'ok' => false,

            'error' =>
                'Random generator failed'
        ],
        500
    );
}


$jobFile =
    $jobDir
    . '/job_'
    . $messageId
    . '_'
    . $random
    . '.json';


if (
    file_put_contents(
        $jobFile,
        $raw,
        LOCK_EX
    )
    === false
) {

    flock(
        $runtimeLock,
        LOCK_UN
    );

    fclose(
        $runtimeLock
    );


    respond(
        [
            'ok' => false,

            'error' =>
                'Cannot write job file'
        ],
        500
    );
}


@chmod(
    $jobFile,
    0600
);


/*
|--------------------------------------------------------------------------
| Run Python SYNCHRONOUSLY
|--------------------------------------------------------------------------
|
| No nohup.
| No detached child process.
| No fire-and-forget.
|
| Cloudflare Queue waits for the result.
|
*/

$command =

    escapeshellarg(
        $python
    )

    . ' '

    . escapeshellarg(
        $script
    )

    . ' '

    . escapeshellarg(
        $jobFile
    )

    . ' 2>>'

    . escapeshellarg(
        $stderrLog
    );


$output = [];

$exitCode = 0;


$started =
    microtime(true);


exec(
    $command,
    $output,
    $exitCode
);


$elapsed =
    microtime(true)
    - $started;


@unlink(
    $jobFile
);


/*
|--------------------------------------------------------------------------
| Processor result
|--------------------------------------------------------------------------
*/

$result =
    extractJsonResult(
        $output
    );


if (
    $exitCode !== 0
    ||
    !is_array(
        $result
    )
    ||
    !(
        $result['ok']
        ?? false
    )
) {

    flock(
        $runtimeLock,
        LOCK_UN
    );

    fclose(
        $runtimeLock
    );


    /*
     * HTTP 500 means Cloudflare Queue
     * will retry this job.
     */

    respond(
        [
            'ok' => false,

            'error' =>
                'Python processor failed',

            'exit_code' =>
                $exitCode,

            'processor_result' =>
                $result,

            'elapsed_sec' =>
                round(
                    $elapsed,
                    3
                ),
        ],
        500
    );
}


/*
|--------------------------------------------------------------------------
| Mark THIS MESSAGE as complete
|--------------------------------------------------------------------------
*/

$donePayload = [

    'message_id' =>
        $messageId,

    'completed_at' =>
        time(),

    'processor_result' =>
        $result,
];


$tempDone =
    $doneFile

    . '.tmp.'

    . bin2hex(
        random_bytes(4)
    );


file_put_contents(

    $tempDone,

    json_encode(
        $donePayload,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES
    ),

    LOCK_EX
);


@chmod(
    $tempDone,
    0600
);


@rename(
    $tempDone,
    $doneFile
);


/*
|--------------------------------------------------------------------------
| Unlock
|--------------------------------------------------------------------------
*/

flock(
    $runtimeLock,
    LOCK_UN
);


fclose(
    $runtimeLock
);


/*
|--------------------------------------------------------------------------
| Success
|--------------------------------------------------------------------------
*/

respond([
    'ok' => true,

    'demo' =>
        'created',

    'message_id' =>
        $messageId,

    'elapsed_sec' =>
        round(
            $elapsed,
            3
        ),

    'processor_result' =>
        $result,
]);