# write_analysis_md
# -----------------
# Genera un archivo analysis.md con frontmatter valido para el registry.
# El dir_path se calcula relativo a FN_REGISTRY_ROOT.
#
# USO (sourced):
#   source write_analysis_md.sh
#   write_analysis_md <analysis_dir> <name> <description> [tags_csv]
#
# EJEMPLOS:
#   write_analysis_md projects/aurgi/analysis/sale_prices sale_prices "Comprobacion precios"
#   write_analysis_md analysis/finanzas finanzas "Exploracion gastos" "finanzas,personal"

write_analysis_md() {
    local analysis_dir="${1:-}"
    local name="${2:-}"
    local description="${3:-}"
    local tags_csv="${4:-}"

    if [ -z "$analysis_dir" ] || [ -z "$name" ]; then
        echo "Uso: write_analysis_md <analysis_dir> <name> <description> [tags_csv]" >&2
        return 1
    fi

    # dir_path relativo a FN_REGISTRY_ROOT
    local registry_root="${FN_REGISTRY_ROOT:-}"
    if [ -z "$registry_root" ]; then
        # Intenta deducirlo: buscar registry.db hacia arriba
        local probe="$(cd "$analysis_dir" && pwd)"
        while [ "$probe" != "/" ] && [ ! -f "$probe/registry.db" ]; do
            probe="$(dirname "$probe")"
        done
        registry_root="$probe"
    fi

    local abs_dir="$(cd "$analysis_dir" && pwd)"
    local rel_dir="${abs_dir#${registry_root}/}"

    # Construir array YAML de tags
    local tags_yaml="[]"
    if [ -n "$tags_csv" ]; then
        tags_yaml="[$(echo "$tags_csv" | sed 's/,/, /g')]"
    fi

    local md_path="${analysis_dir}/analysis.md"
    cat > "$md_path" << EOF
---
name: ${name}
lang: py
domain: datascience
description: "${description}"
tags: ${tags_yaml}
uses_functions: []
uses_types: []
framework: "jupyterlab"
entry_point: "notebooks/main.ipynb"
dir_path: "${rel_dir}"
repo_url: ""
---

## Notas

${description}
EOF

    echo "$md_path"
}
