<?php

declare(strict_types=1);

$root = rtrim((string)getenv('POC_TARGET_ROOT'), '/');
$baseUrl = rtrim((string)getenv('POC_BASE_URL'), '/');
if ($root === '' || $baseUrl === '' || !is_dir($root . '/public')) exit(2);

$chunk = static function (string $type, string $data): string {
    return pack('N', strlen($data)) . $type . $data . pack('N', crc32($type . $data));
};
$binary = "\x89PNG\r\n\x1a\n"
    . $chunk('IHDR', pack('NNCCCCC', 1, 1, 8, 6, 0, 0, 0))
    . $chunk('IDAT', gzcompress("\x00\xff\x00\x00\xff"))
    . $chunk('IEND', '');
if (!getimagesizefromstring($binary)) throw new RuntimeException('PNG fixture invalid');
$relative = 'static/upload/mocatch/20260930/image/CDXIMG-PARITY/' . sha1($binary) . '.png';
$absolute = $root . '/public/' . $relative;
$leaf = dirname($absolute);
if (is_file($absolute)) throw new RuntimeException('Test image already exists; refuse overwrite');

$post = static function (array $form) use ($baseUrl): array {
    $context = stream_context_create(['http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
        'content' => http_build_query($form, '', '&', PHP_QUERY_RFC3986),
        'timeout' => 15, 'ignore_errors' => true,
    ]]);
    $body = file_get_contents($baseUrl . '/api/mocatch/image', false, $context);
    if (!is_string($body)) throw new RuntimeException('No image HTTP response');
    $status = null;
    $contentType = null;
    foreach ($http_response_header as $header) {
        if (preg_match('/^HTTP\/\S+\s+(\d{3})/', $header, $match)) $status = (int)$match[1];
        if (stripos($header, 'Content-Type:') === 0) {
            $contentType = trim(substr($header, strlen('Content-Type:')));
        }
    }
    return ['http_status' => $status, 'content_type' => $contentType, 'body' => $body];
};

try {
    $form = [
        'NameID' => 'CDXIMG-PARITY',
        'TestTime' => '2026-09-30 12:00:00',
        'img' => 'data:image/png;base64,' . base64_encode($binary),
    ];
    $first = $post($form);
    if ($first !== ['http_status' => 200, 'content_type' => 'text/plain; charset=utf-8',
            'body' => $relative]
        || !is_file($absolute)
        || file_get_contents($absolute) !== $binary) {
        throw new RuntimeException('MOCATCH image HTTP/file readback mismatch');
    }
    $duplicate = $post($form);
    if ($duplicate !== $first || !is_file($absolute)) {
        throw new RuntimeException('Duplicate image upload changed response or removed file');
    }
    $invalid = $post(['NameID' => 'CDXIMG-PARITY', 'img' => 'invalid-base64']);
    if ($invalid['http_status'] !== 400 || $invalid['body'] !== 'image is empty') {
        throw new RuntimeException('Invalid image payload was not rejected');
    }
    echo json_encode(['status' => 'passed', 'success_response' => $first,
        'duplicate_same_path' => true, 'invalid_rejected' => true,
        'file_sha1' => sha1($binary), 'file_bytes' => strlen($binary)],
        JSON_UNESCAPED_SLASHES) . PHP_EOL;
} finally {
    if (is_file($absolute)) unlink($absolute);
    if (is_dir($leaf)) @rmdir($leaf);
    if (is_file($absolute)) throw new RuntimeException('Test image cleanup failed');
}
