import { matchScope } from "../../../core/src/match/scope.js";
import type { DetectorContext } from "../../../core/src/sdk/detector.js";
import type { MatrixCell } from "../../../schema/src/records/context.js";
import type { ConsistencyRuleId } from "./types.js";

export function isIntentionallyExcepted(
  context: DetectorContext,
  cell: MatrixCell,
  detectorId: string,
  ruleId: ConsistencyRuleId,
): boolean {
  for (const contract of context.readStores.contracts.confirmedContracts()) {
    if (!context.readStores.contracts.isActive(contract.id)) {
      continue;
    }
    if (
      !context.readStores.authoritativeContracts.has(`${contract.id}@${contract.version}`)
    ) {
      continue;
    }

    const match = matchScope(contract.applicableScope, {
      detector: { id: detectorId, version: "1.0.0" },
      target: cell.url,
      contextKind: "browser",
      dimensions: {
        route: cell.routeId,
        role: cell.role,
        rule: ruleId,
      },
      contractVersion: contract.applicableScope.contractVersion,
      now: context.readStores.now,
    });

    if (match.matched) {
      return true;
    }
  }

  return false;
}
