package com.correx.core.toolintent.rules

import com.correx.core.tools.contract.ParamRole

/**
 * Flattens a raw tool-call parameter value into candidate strings for rule
 * inspection. A declared param may arrive as a plain String (e.g. a path) or a
 * List<*> (e.g. shell `argv`); both are reduced to strings.
 */
internal fun extractParamStrings(value: Any?): List<String> = when (value) {
    is String -> listOf(value)
    is List<*> -> value.mapNotNull { it?.toString() }
    else -> emptyList()
}

/**
 * The path-like argument strings of a tool call: the values of params declared
 * [ParamRole.PATH], or — when none are declared — any string value that looks like a
 * path. Shared by the path-containment and write-manifest rules so both judge exactly
 * the same set of targets.
 */
internal fun candidatePathStrings(paramRoles: Map<String, ParamRole>, parameters: Map<String, Any>): List<String> {
    val declared = paramRoles.filterValues { it == ParamRole.PATH }.keys
    return if (declared.isNotEmpty()) {
        declared.flatMap { extractParamStrings(parameters[it]) }
    } else {
        parameters.values.filterIsInstance<String>().filter { it.looksLikePath() }
    }
}

private fun String.looksLikePath(): Boolean =
    isNotBlank() && (startsWith("/") || startsWith("~") || contains("/") || contains(".."))
