<?php

require __DIR__ . '/../vendor/autoload.php';

$app = require __DIR__ . '/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

$service = app(App\Services\LoadDocumentService::class);
$ref = new ReflectionClass($service);
$extractText = $ref->getMethod('extractText');
$extractText->setAccessible(true);
$extractFields = $ref->getMethod('extractFields');
$extractFields->setAccessible(true);
$inferMiles = $ref->getMethod('inferMilesWhenMissing');
$inferMiles->setAccessible(true);

$company = App\Models\Company::query()->first();
$driver = App\Models\Driver::query()->where('company_id', $company?->id)->orderBy('id')->first();

if (!$company) {
    fwrite(STDERR, "No company found for inference audit.\n");
    exit(1);
}

$folders = [
    'working' => 'C:/Users/Hp/Downloads/working',
    'not_working' => 'C:/Users/Hp/Downloads/not working',
];

$rows = [];

foreach ($folders as $group => $folder) {
    foreach (glob($folder . '/*.pdf') ?: [] as $path) {
        $text = (string) $extractText->invoke($service, $path, 'pdf');
        $fields = (array) $extractFields->invoke($service, $text);

        $rawMiles = isset($fields['miles']) ? (float) $fields['miles'] : null;
        $docRate = isset($fields['gross_rate']) ? (float) $fields['gross_rate'] : null;

        $inferredMiles = $inferMiles->invoke(
            $service,
            $rawMiles,
            $docRate,
            [],
            $company,
            $driver
        );

        $rows[] = [
            'group' => $group,
            'file' => basename($path),
            'raw_miles' => $rawMiles,
            'gross_rate' => $docRate,
            'inferred_miles' => $inferredMiles,
            'will_save' => (($inferredMiles ?? 0) > 0 || ($docRate ?? 0) > 0) ? 'yes' : 'no',
        ];
    }
}

usort($rows, fn ($a, $b) => strcmp($a['group'] . $a['file'], $b['group'] . $b['file']));

$outPath = __DIR__ . '/audit_inference_results.json';
file_put_contents($outPath, json_encode($rows, JSON_PRETTY_PRINT));

echo "Wrote: {$outPath}" . PHP_EOL;
echo "Rows: " . count($rows) . PHP_EOL;
