<?php

namespace App\Services\Forecasting;

use Carbon\CarbonInterface;

/**
 * Structural time-leak detector.
 *
 * For every (training week, feature) pair, verifies that every source
 * date the feature reads is strictly before the target Monday. A
 * source date on or after the target Monday is leakage and the
 * backtest harness must refuse to run.
 *
 * This is the *primary* leak defence. The accuracy>75% smell test on
 * the resulting backtest is a secondary check.
 */
final class LeakDetector
{
    /** @param array<int, CarbonInterface> $trainingMondays */
    public function validate(FeatureSpec $spec, array $trainingMondays): LeakReport
    {
        $leaks = [];

        foreach ($trainingMondays as $target) {
            foreach ($spec->features as $feature) {
                foreach ($feature->sourceDates($target) as $source) {
                    if ($source->greaterThanOrEqualTo($target)) {
                        $leaks[] = [
                            'feature' => $feature->name(),
                            'target_monday' => $target->toDateString(),
                            'source_date' => $source->toDateString(),
                        ];
                    }
                }
            }
        }

        return new LeakReport($leaks);
    }
}
