package com.correx.core.kernel.orchestration

/**
 * Deterministic recovery evidence for an unambiguous package-not-found (Vikunja #192). A registry
 * 404 means the dependency does not exist — retrying the installer, pinning a version, or switching
 * package managers cannot fix it (the 2026-07-16 audition burned 26 inferences doing exactly that).
 * Parse the offending name out of npm/yarn/pnpm output and hand back a directive that points at the
 * *manifest*, not the installer. Empty string when no 404 is detected, so callers concatenate
 * unconditionally. Pure over the tool output (already recorded on the ToolReceipt) — no new event.
 */
internal fun packageNotFoundAdvisory(output: String): String {
    val pkg = PACKAGE_NOT_FOUND_PATTERNS.firstNotNullOfOrNull { it.find(output)?.groupValues?.get(1) }
        ?.replace("%2f", "/", ignoreCase = true) // npm URL-encodes the scope slash
        ?.trim()
        ?.takeIf { it.isNotEmpty() }
        ?: return ""
    // Strip a trailing @version so the name matches the manifest key.
    val name = if (pkg.startsWith("@")) {
        "@" + pkg.removePrefix("@").substringBefore('@')
    } else {
        pkg.substringBefore('@')
    }
    return "\nPACKAGE_NOT_FOUND: '$name' does not exist in the registry (404). Do NOT retry the " +
        "installer, pin a version, or switch package managers — none can create a nonexistent " +
        "package. Edit the manifest (e.g. package.json) to remove or correct '$name', then reinstall."
}

// Registry-404 shapes across npm/yarn/pnpm. Group 1 is the offending package spec.
//  npm modern:  npm error 404  '@types/vite@^4.0.0' is not in this registry.
//  npm/GET url: npm error 404 Not Found - GET https://registry.npmjs.org/@types%2fvite - Not found
//  yarn:        error ... https://registry.yarnpkg.com/@types%2fvite: Not found
//  pnpm:        ERR_PNPM_FETCH_404 ... GET https://registry.npmjs.org/@types%2fvite: Not Found - 404
private val PACKAGE_NOT_FOUND_PATTERNS = listOf(
    Regex("""404[^\n']*'([^'\n]+)'"""),
    Regex("""404[^\n]*?registry\.\S+?/(@?[\w.%-]+(?:/[\w.%-]+)?)"""),
)
