import { z } from "zod";

export type VersionCheck = "compat-range" | "erp-kit-version" | "skills-version" | "manifest-parse";
export type VersionSeverity = "error" | "warning" | "info";

export interface VersionFinding {
  severity: VersionSeverity;
  check: VersionCheck;
  subject: string;
  message: string;
}

const DependencyMap = z.record(z.string(), z.string());

export const ManifestSchema = z.object({
  dependencies: DependencyMap.optional(),
  devDependencies: DependencyMap.optional(),
  peerDependencies: DependencyMap.optional(),
  optionalDependencies: DependencyMap.optional(),
});

export type Manifest = z.infer<typeof ManifestSchema>;

export interface WorkspacePackage {
  relativePath: string;
  manifest: Manifest;
}

// Detects `<protocol>:` specifiers (catalog:, workspace:, npm:, git+…) that aren't a comparable semver.
export function isNonSemverSpecifier(declared: string): boolean {
  return /^[a-z][a-z0-9+.-]*:/i.test(declared);
}

export function readDeclaredVersion(manifest: Manifest, pkgName: string): string | undefined {
  return (
    manifest.dependencies?.[pkgName] ??
    manifest.devDependencies?.[pkgName] ??
    manifest.peerDependencies?.[pkgName] ??
    manifest.optionalDependencies?.[pkgName]
  );
}
