package com.easyagents.federation.sql.execute;

import com.easyagents.federation.sql.adapter.AdapterCompatibility;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;

/**
 * Adapter 执行单个物理分片 Explain 的上下文。
 *
 * @param sql 目标数据库方言参数化 SQL
 * @param parameters 已按分片参数映射排序的参数
 * @param dataSource 调用方提供的 DataSource
 * @param compatibility 数据库与驱动兼容性
 * @param adapterOptions 不含凭据的 Adapter 选项
 * @param queryTimeoutSeconds Explain 超时秒数
 * @param executionGuard 统一查询终态与截止时间检查器
 */
public record FederationFragmentExplainContext(
    String sql,
    List<SqlParameter> parameters,
    DataSource dataSource,
    AdapterCompatibility compatibility,
    Map<String, String> adapterOptions,
    int queryTimeoutSeconds,
    FederationExecutionGuard executionGuard
) {

    /**
     * 校验并创建不可变 Explain 上下文。
     */
    public FederationFragmentExplainContext {
        if (sql == null || sql.isBlank() || dataSource == null || compatibility == null) {
            throw new IllegalArgumentException("fragment Explain context is incomplete");
        }
        if (queryTimeoutSeconds < 0) {
            throw new IllegalArgumentException("queryTimeoutSeconds must not be negative");
        }
        parameters = List.copyOf(parameters == null ? List.of() : parameters);
        adapterOptions = Map.copyOf(adapterOptions == null ? Map.of() : adapterOptions);
        executionGuard = executionGuard == null
            ? FederationExecutionGuard.none()
            : executionGuard;
    }

    /**
     * 保留旧 Adapter 与调用方的兼容构造器。
     *
     * @param sql 目标数据库 SQL
     * @param parameters 参数
     * @param dataSource 数据源
     * @param compatibility 兼容性信息
     * @param adapterOptions Adapter 选项
     * @param queryTimeoutSeconds Explain 超时秒数
     */
    public FederationFragmentExplainContext(
        String sql,
        List<SqlParameter> parameters,
        DataSource dataSource,
        AdapterCompatibility compatibility,
        Map<String, String> adapterOptions,
        int queryTimeoutSeconds
    ) {
        this(
            sql,
            parameters,
            dataSource,
            compatibility,
            adapterOptions,
            queryTimeoutSeconds,
            FederationExecutionGuard.none()
        );
    }
}
