import semver from "semver";
import {
  isNonSemverSpecifier,
  readDeclaredVersion,
  type VersionFinding,
  type WorkspacePackage,
} from "./shared";

export interface CompatEntry {
  range: string;
  rationale: string;
}

export const compat: Record<string, CompatEntry> = {
  "@tailor-platform/sdk": {
    range: "^1.55.0",
    rationale:
      "The testing skill generates tests that use createKyselyMock (shipped since 1.55.0).",
  },
  "@tailor-platform/app-shell": {
    range: "^1.3.0",
    rationale:
      "The frontend skill reads the app-shell-patterns skill bundled in this package (shipped since 1.3.0).",
  },
};

export function checkCompatRange(packages: WorkspacePackage[]): VersionFinding[] {
  const findings: VersionFinding[] = [];
  for (const [pkgName, entry] of Object.entries(compat)) {
    for (const pkg of packages) {
      const declared = readDeclaredVersion(pkg.manifest, pkgName);
      if (declared === undefined) continue;
      if (isNonSemverSpecifier(declared)) {
        findings.push({
          severity: "warning",
          check: "compat-range",
          subject: pkg.relativePath,
          message: `${pkgName}@${declared} uses a non-semver specifier; cannot verify against compat range ${entry.range}. Pin an exact version.`,
        });
        continue;
      }
      if (semver.valid(declared)) {
        if (!semver.satisfies(declared, entry.range)) {
          findings.push({
            severity: "error",
            check: "compat-range",
            subject: pkg.relativePath,
            message: `${pkgName}@${declared} does not satisfy erp-kit compat range ${entry.range}. ${entry.rationale}`,
          });
        }
        continue;
      }
      if (!semver.validRange(declared)) {
        findings.push({
          severity: "error",
          check: "compat-range",
          subject: pkg.relativePath,
          message: `${pkgName}@${declared} is not a valid version or range. Pin to an exact version inside ${entry.range}.`,
        });
        continue;
      }
      // valid range that is not a single version
      if (semver.subset(declared, entry.range)) {
        findings.push({
          severity: "warning",
          check: "compat-range",
          subject: pkg.relativePath,
          message: `${pkgName}@${declared} should be pinned to an exact version so an unintended one can't be installed.`,
        });
      } else {
        findings.push({
          severity: "error",
          check: "compat-range",
          subject: pkg.relativePath,
          message: `${pkgName}@${declared} admits versions outside erp-kit compat range ${entry.range}; pin an exact version. ${entry.rationale}`,
        });
      }
    }
  }
  return findings;
}
