<?php

declare(strict_types=1);

$base = rtrim((string)getenv('POC_BASE_URL'), '/');
$root = (string)getenv('POC_APP_ROOT');
$dialect = (string)getenv('POC_DIALECT');
if ($base === '' || !in_array($dialect, ['mysql', 'dm'], true)
    || strpos($root, '/tmp/zhct-') !== 0
    || !is_file($root . '/application/base/Security.php')) {
    throw new RuntimeException('Private upload runtime missing');
}
$boundary = json_decode((string)file_get_contents($base . '/__poc_upload_boundary'), true);
if (!is_array($boundary) || empty($boundary['isolated_upload_directory'])
    || empty($boundary['oss_local_stub']) || empty($boundary['external_stubs'])) {
    throw new RuntimeException('Local-only OSS/file boundary not proven');
}
$brandDir = $root . '/public/static/upload/brandLogo';
if (file_exists($brandDir) || is_link($brandDir)) {
    throw new RuntimeException('Brand upload directory already exists; stop rather than touch existing files');
}
$uploadParent = realpath($root . '/public/static/upload');
if ($uploadParent !== $root . '/public/static/upload') {
    throw new RuntimeException('Brand upload parent is not the private runtime directory');
}

require_once $root . '/application/base/Security.php';
$marker = 'CDXPARSTUP' . strtoupper(bin2hex(random_bytes(6)));
$token = \app\base\Security::encrypt(implode("\t", ['0', $marker, $marker, '0', '', '', $marker]));
$png = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9sZAAAAABJRU5ErkJggg==', true);
$image = is_string($png) ? getimagesizefromstring($png) : false;
if (!is_array($image) || $image[0] !== 1 || $image[1] !== 1) {
    throw new RuntimeException('One-pixel PNG fixture invalid');
}
$request = static function (array $fields, ?string $fileName = null, ?string $bytes = null,
    string $mime = 'image/png') use ($base, $token): array {
    $boundaryText = 'CDXUpload' . bin2hex(random_bytes(8));
    $body = '';
    foreach ($fields as $key => $value) {
        $body .= '--' . $boundaryText . "\r\n"
            . 'Content-Disposition: form-data; name="' . $key . '"' . "\r\n\r\n"
            . $value . "\r\n";
    }
    if ($fileName !== null) {
        $body .= '--' . $boundaryText . "\r\n"
            . 'Content-Disposition: form-data; name="file_path"; filename="' . $fileName . '"' . "\r\n"
            . 'Content-Type: ' . $mime . "\r\n\r\n" . (string)$bytes . "\r\n";
    }
    $body .= '--' . $boundaryText . "--\r\n";
    $headers = 'Content-Type: multipart/form-data; boundary=' . $boundaryText . "\r\n"
        . 'token: ' . $token . "\r\n";
    $context = stream_context_create(['http' => [
        'method' => 'POST', 'header' => $headers, 'content' => $body,
        'timeout' => 30, 'ignore_errors' => true,
    ]]);
    $raw = file_get_contents($base . '/p/brandLogo/upload', false, $context);
    $responseHeaders = $http_response_header ?? [];
    $contentType = '';
    foreach ($responseHeaders as $header) {
        if (stripos($header, 'Content-Type:') === 0) $contentType = $header;
    }
    if (strpos((string)($responseHeaders[0] ?? ''), ' 200 ') === false
        || stripos($contentType, 'application/json') === false) {
        throw new RuntimeException('Upload HTTP status/content type mismatch');
    }
    $response = is_string($raw) ? json_decode($raw, true) : null;
    if (!is_array($response)) throw new RuntimeException('Upload HTTP response is not JSON');
    return $response;
};
$shape = static function ($value) use (&$shape): string {
    if (!is_array($value)) return gettype($value);
    $keys = array_keys($value);
    if ($keys === range(0, count($keys) - 1)) {
        return '[' . implode(',', array_map($shape, $value)) . ']';
    }
    sort($keys, SORT_STRING);
    $parts = [];
    foreach ($keys as $key) $parts[] = $key . ':' . $shape($value[$key]);
    return '{' . implode(',', $parts) . '}';
};
$results = [];
$storedFile = '';
$dateDir = '';
try {
    $missing = $request(['terminal_code' => 'pc', 'asset_type' => 'logo']);
    $results['missing_file'] = [
        'status' => (int)($missing['code'] ?? 0) !== 0 && !file_exists($brandDir)
            ? 'tested-pass' : 'tested-fail',
        'code' => $missing['code'] ?? null,
        'message' => $missing['message'] ?? null,
    ];
    $badTerminal = $request(['terminal_code' => 'not-supported', 'asset_type' => 'logo'],
        $marker . '.png', $png);
    $results['invalid_terminal'] = [
        'status' => (int)($badTerminal['code'] ?? 0) !== 0 && !file_exists($brandDir)
            ? 'tested-pass' : 'tested-fail',
        'message' => $badTerminal['message'] ?? null,
    ];
    $invalidMime = $request(['terminal_code' => 'pc', 'asset_type' => 'logo'],
        $marker . '.png', 'not-a-png', 'text/plain');
    $results['invalid_mime_and_bytes'] = [
        'status' => (int)($invalidMime['code'] ?? 0) !== 0 && !file_exists($brandDir)
            ? 'tested-pass' : 'tested-fail',
        'message' => $invalidMime['message'] ?? null,
    ];
    $empty = $request(['terminal_code' => 'pc', 'asset_type' => 'logo'],
        $marker . '.png', '');
    $results['empty_file'] = [
        'status' => (int)($empty['code'] ?? 0) !== 0 && !file_exists($brandDir)
            ? 'tested-pass' : 'tested-fail',
        'message' => $empty['message'] ?? null,
    ];
    $oversize = $request(['terminal_code' => 'pc', 'asset_type' => 'logo'],
        $marker . '.png', str_repeat('A', 5 * 1024 * 1024 + 1));
    $results['over_5mb'] = [
        'status' => (int)($oversize['code'] ?? 0) !== 0 && !file_exists($brandDir)
            ? 'tested-pass' : 'tested-fail',
        'message' => $oversize['message'] ?? null,
    ];

    $success = $request(['terminal_code' => 'pc', 'asset_type' => 'logo'],
        $marker . '.png', $png);
    $data = $success['data'] ?? [];
    $path = (string)($data['file_path'] ?? '');
    if (!preg_match('#^static/upload/brandLogo/[0-9]{8}/[A-Za-z0-9_.-]+$#D', $path)) {
        throw new RuntimeException('Upload output path is outside brand directory');
    }
    $storedFile = $root . '/public/' . $path;
    $dateDir = dirname($storedFile);
    $actualPath = realpath($storedFile);
    $safeFile = $actualPath === $storedFile
        && strpos($actualPath, $brandDir . '/') === 0 && !is_link($storedFile);
    $contentsMatch = $safeFile && is_file($storedFile)
        && hash_file('sha256', $storedFile) === hash('sha256', $png);
    $results['png_1px'] = [
        'status' => (int)($success['code'] ?? -1) === 0 && $contentsMatch
            && ($success['message'] ?? null) === '上传成功'
            && ($data['asset_type'] ?? null) === 'logo'
            && ($data['source_file_path'] ?? null) === $path
            && ($data['file_name'] ?? null) === $marker . '.png'
            && ($data['mime_type'] ?? null) === 'image/png'
            && ($data['file_size'] ?? null) === strlen($png)
            && ($data['image_width'] ?? null) === 1
            && ($data['image_height'] ?? null) === 1
            && ($data['url'] ?? null) === '/' . $path
            ? 'tested-pass' : 'tested-fail',
        'code' => $success['code'] ?? null,
        'saved_bytes' => $safeFile && is_file($storedFile) ? filesize($storedFile) : null,
        'content_sha256_matches' => $contentsMatch,
        'path_is_private' => $safeFile,
        'shape_sha256' => hash('sha256', $shape($success)),
    ];
} finally {
    if ($storedFile !== '' && is_file($storedFile)
        && strpos($storedFile, $brandDir . '/') === 0 && !is_link($storedFile)) {
        unlink($storedFile);
    }
    if ($dateDir !== '' && is_dir($dateDir)) rmdir($dateDir);
    if (is_dir($brandDir)) rmdir($brandDir);
    if (file_exists($brandDir)) {
        throw new RuntimeException('Brand test upload directory not empty after exact cleanup');
    }
}
$results['cleanup'] = ['status' => 'tested-pass', 'brand_directory_exists' => false];
echo json_encode(['dialect' => $dialect, 'module' => 'store-brand-upload',
    'results' => $results], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
