<?php
declare(strict_types=1);

// Pure local/source contract test. Never boots ThinkPHP, opens a DB, or sends HTTP.
$root = dirname(__DIR__, 4) . '/zhctproject/ai_api/app/api/service';
$targets = ['WellandScale.php', 'YunkangbaoScale.php'];
$bad = [];
foreach ($targets as $name) {
    $source = file_get_contents($root . '/' . $name);
    if (!is_string($source)
        || !preg_match('/public function dates\(int \$aiUserId\): array\s*\{(.*?)\n    \}/s', $source, $match)) {
        fwrite(STDERR, "RED: dates array contract not found in {$name}\n");
        exit(1);
    }
    $body = $match[1];
    if (preg_match('/\$dates\s*=\s*date\s*\(/', $body)) {
        $bad[] = $name;
    }
    if (!preg_match('/if\s*\(\s*empty\(\$dates\)\s*\)/', $body)) {
        fwrite(STDERR, "RED: empty result branch missing in {$name}\n");
        exit(1);
    }
}

// Prove the PHP return-type mismatch without invoking either database service.
$minimal = static function (): array {
    $dates = [];
    if (empty($dates)) {
        $dates = date('Y-m-d');
    }
    return $dates;
};
try {
    $minimal();
    fwrite(STDERR, "RED: runtime did not enforce array return type\n");
    exit(1);
} catch (TypeError $expected) {
    // This is the PHP behavior that the source-level check protects against.
}

if ($bad !== []) {
    fwrite(STDERR, 'RED: dates(): array can return string on empty rows in '
        . implode(', ', $bad) . "\n");
    exit(1);
}
echo "GREEN: no string fallback in either dates(): array source\n";
