#! Template rendering daemon functions
#!
#! Provides high-performance Jinja2 template rendering via HTTP API.
#! The CLI daemon's Tera engine offers 50-100x better performance than
#! spawning a new Nushell process for each template render.
#!
#! Performance:
#! - Single render: ~4-10ms (vs ~500ms with Nushell spawning)
#! - Batch 10 renders: ~50-60ms (vs ~5500ms)
#! - Batch 100 renders: ~600-700ms (vs ~55000ms)

use ../env.nu [get-cli-daemon-url]

# Render a Jinja2 template with the given context
#
# Uses the CLI daemon's Tera engine for fast in-process template rendering.
# This is significantly faster than spawning a new Nushell process.
#
# # Arguments
# * `template` - Template content (Jinja2 syntax)
# * `context` - Context record with template variables
# * `--name` - Optional template name for error reporting
#
# # Returns
# Rendered template content or error if rendering failed
#
# # Example
# ```nushell
# let template = "Hello {{ name }}!"
# let context = {name: "World"}
# tera-render-daemon $template $context --name greeting
# # Output: Hello World!
# ```
export def tera-render-daemon [
    template: string
    context: record
    --name: string = "template"
] -> string {
    let daemon_url = (get-cli-daemon-url)

    # Convert context record to JSON object
    let context_json = ($context | to json | from json)

    # Build request
    let request = {
        template: $template
        context: $context_json
        name: $name
    }

    # Send to daemon's Tera endpoint
    let response = (
        http post $"($daemon_url)/tera/render" $request
        --raw
    )

    # Parse response
    let parsed = ($response | from json)

    # Check for error
    if ($parsed.error? != null) {
        error make {msg: $parsed.error}
    }

    # Return rendered output
    $parsed.rendered
}

# Get template rendering statistics from daemon
#
# Returns statistics about template renders since daemon startup or last reset.
#
# # Returns
# Record with:
# - `total_renders`: Total number of templates rendered
# - `total_errors`: Number of rendering errors
# - `total_time_ms`: Total time spent rendering (milliseconds)
# - `avg_time_ms`: Average time per render
export def tera-daemon-stats [] -> record {
    let daemon_url = (get-cli-daemon-url)

    let response = (http get $"($daemon_url)/tera/stats")

    $response | from json
}

# Reset template rendering statistics on daemon
#
# Clears all counters and timing statistics.
export def tera-daemon-reset-stats [] -> void {
    let daemon_url = (get-cli-daemon-url)

    http post $"($daemon_url)/tera/stats/reset" ""
}

# Check if CLI daemon is running and Tera rendering is available
#
# # Returns
# `true` if daemon is running with Tera support, `false` otherwise
export def is-tera-daemon-available [] -> bool {
    let result = (do {
        let daemon_url = (get-cli-daemon-url)
        let response = (http get $"($daemon_url)/info" --timeout 500ms)

        # Check if tera-rendering is in features list
        ($response | from json | .features | str contains "tera-rendering")
    } | complete)

    if $result.exit_code != 0 {
        false
    } else {
        $result.stdout
    }
}

# Start using Tera daemon for rendering (if available)
#
# This function checks if the daemon is running and prints a status message.
# It's useful for diagnostics.
export def ensure-tera-daemon [] -> void {
    if (is-tera-daemon-available) {
        print "✅ Tera daemon is available and running"
    } else {
        print "⚠️  Tera daemon is not available"
        print "   CLI daemon may not be running at http://localhost:9091"
    }
}

# Render multiple templates in batch mode
#
# Renders a list of templates sequentially. This is faster than calling
# tera-render-daemon multiple times due to daemon connection reuse.
#
# # Arguments
# * `templates` - List of records with `template` and `context` fields
#
# # Returns
# List of rendered outputs or error messages
#
# # Example
# ```nushell
# let templates = [
#     {template: "Hello {{ name }}", context: {name: "Alice"}}
#     {template: "Goodbye {{ name }}", context: {name: "Bob"}}
# ]
# tera-render-batch $templates
# # Output: [Hello Alice, Goodbye Bob]
# ```
export def tera-render-batch [
    templates: list<record>
] -> list<string> {
    let results = []

    for template_def in $templates {
        let rendered = (
            tera-render-daemon
                $template_def.template
                $template_def.context
                --name ($template_def.name? | default "batch")
        )
        $results | append $rendered
    }

    $results
}

# Profile template rendering performance
#
# Renders a template multiple times and reports timing statistics.
# Useful for benchmarking and performance optimization.
#
# # Arguments
# * `template` - Template to render
# * `context` - Context for rendering
# * `--iterations` - Number of times to render (default: 10)
# * `--name` - Template name for reporting
#
# # Returns
# Record with performance metrics
export def tera-profile [
    template: string
    context: record
    --iterations: int = 10
    --name: string = "profiled"
] -> record {
    let start = (date now)

    # Reset stats before profiling
    tera-daemon-reset-stats

    # Run renders
    for i in 0..<$iterations {
        tera-render-daemon $template $context --name $"($name)_$i"
    }

    let elapsed = ((date now) - $start) | into duration | get total | . / 1_000_000
    let stats = (tera-daemon-stats)

    {
        iterations: $iterations
        total_time_ms: $elapsed
        avg_time_ms: ($elapsed / $iterations)
        daemon_renders: $stats.total_renders
        daemon_avg_time_ms: $stats.avg_time_ms
        daemon_errors: $stats.total_errors
    }
}
