<?php

declare(strict_types=1);

namespace App\Framework\MachineLearning\Migrations;

use App\Framework\Database\ConnectionInterface;
use App\Framework\Database\Migration\Migration;
use App\Framework\Database\Migration\MigrationVersion;
use App\Framework\Database\Schema\Blueprint;
use App\Framework\Database\Schema\Schema;

/**
 * Create ML Confidence Baselines Table
 *
 * Stores historical confidence statistics for drift detection:
 * - Average confidence per model version
 * - Standard deviation for anomaly detection
 * - Last update timestamp
 *
 * Uses ON CONFLICT for upsert pattern - baselines are updated
 * as new predictions come in.
 */
final class CreateMlConfidenceBaselinesTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->createIfNotExists('ml_confidence_baselines', function (Blueprint $table) {
            // Model identification
            $table->string('model_name', 255);
            $table->string('version', 50);

            // Confidence statistics
            $table->decimal('avg_confidence', 5, 4); // Average confidence score
            $table->decimal('std_dev_confidence', 5, 4); // Standard deviation

            // Tracking
            $table->timestamp('updated_at')->useCurrent();

            // Primary key: model_name + version (one baseline per model version)
            $table->primary('model_name', 'version');

            // Index for lookup by model
            $table->index(['model_name'], 'idx_ml_baselines_model');
        });

        $schema->execute();
    }

    public function down(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);
        $schema->dropIfExists('ml_confidence_baselines');
        $schema->execute();
    }

    public function getVersion(): MigrationVersion
    {
        return MigrationVersion::fromTimestamp("2025_01_26_100002");
    }

    public function getDescription(): string
    {
        return "Create ML confidence baselines table for drift detection";
    }
}
