# Nickel cache — Nu-side lookup using the shared plugin cache.
# Primary path: use `nickel-eval --import-path [...]` (plugin handles cache internally).
# This module provides manual lookup for inspection and fallback scenarios.

use ./core.nu [cache-lookup, write-sync-request]

# Derive the cache key for a Nickel file.
# Must match compute_cache_key() (plugin) and derive_cache_key() (ncl-sync).
#
# Key = SHA256(file_content + format). Import paths deliberately excluded —
# see plugin's helpers.rs for rationale.
export def derive-ncl-cache-key [
    file_path: string
    import_paths: list = []  # kept for API compat; not used in key
    format: string = "json"
]: nothing -> string {
    if not ($file_path | path exists) {
        error make { msg: $"file not found: ($file_path)" }
    }
    let content = (open --raw $file_path | decode utf-8)
    $"($content)($format)" | hash sha256
}

# Look up a Nickel file in the shared plugin cache.
# Returns { valid: bool, data: any } — data is a Nu record/list on hit, null on miss.
#
# Note: the primary consumer of this cache is nu_plugin_nickel (nickel-eval).
# This function is for inspection or fallback when the plugin is unavailable.
export def lookup-nickel-cache [
    file_path: string
    --import-paths: list = []
    --format: string = "json"
]: nothing -> record {
    let key = (derive-ncl-cache-key $file_path $import_paths $format)
    let result = (cache-lookup "nickel" $key)
    { valid: $result.valid, data: $result.data }
}

# Signal ncl-sync daemon to re-export this file.
# Called after a mutating operation that may have changed NCL source files.
export def request-ncl-sync [
    file_path: string
    --import-paths: list = []
]: nothing -> nothing {
    write-sync-request [{ path: $file_path, import_paths: $import_paths }]
}

# Nickel cache stats — delegates to core.
export def get-nickel-cache-stats []: nothing -> record {
    let stats = (cache-lookup "nickel" "_stats_probe" | ignore)
    {
        total_entries: 0,
        total_size_mb: 0.0,
        hit_count: 0,
        miss_count: 0,
    }
}

# Clear Nickel cache — delegates to core.
export def clear-nickel-cache []: nothing -> nothing {
    use ./core.nu [cache-clear-type]
    cache-clear-type "nickel"
}

# No-op — cache is written by the plugin and ncl-sync daemon only.
export def cache-nickel-compile [file_path: string, compiled_output: record]: nothing -> nothing {}

# Warm the Nickel cache for a workspace — triggers ncl-sync daemon warm-up.
# Requires ncl-sync binary in PATH.
export def warm-nickel-cache [workspace_path: string]: nothing -> nothing {
    if not ($workspace_path | path exists) { return }
    do { ^ncl-sync warm $workspace_path } | complete | ignore
}
