#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2025-2026 Marcus Quinn
# =============================================================================
# Tech Stack Format Library -- Output formatting for lookup and reverse results
# =============================================================================
# Covers terminal table and markdown formatting for both tech-stack lookup
# results (multi-provider merged output) and reverse lookup results.
#
# Usage: source "${SCRIPT_DIR}/tech-stack-format-lib.sh"
#
# Dependencies:
#   - shared-constants.sh (CYAN, GREEN, YELLOW, NC)
#   - VERSION constant from tech-stack-helper.sh (orchestrator)
#
# Part of aidevops framework: https://aidevops.sh

# Apply strict mode only when executed directly (not when sourced)
[[ "${BASH_SOURCE[0]}" == "${0}" ]] && set -euo pipefail

# Include guard
[[ -n "${_TECH_STACK_FORMAT_LIB_LOADED:-}" ]] && return 0
_TECH_STACK_FORMAT_LIB_LOADED=1

if [[ -z "${SCRIPT_DIR:-}" ]]; then
	_lib_path="${BASH_SOURCE[0]%/*}"
	[[ "$_lib_path" == "${BASH_SOURCE[0]}" ]] && _lib_path="."
	SCRIPT_DIR="$(cd "$_lib_path" && pwd)"
	unset _lib_path
fi

# =============================================================================
# Lookup Result Formatting
# =============================================================================

# Format merged results as a terminal table
format_table() {
	local json="$1"

	local url domain tech_count provider_count scan_time
	url=$(echo "$json" | jq -r '.url' 2>/dev/null)
	domain=$(echo "$json" | jq -r '.domain' 2>/dev/null)
	tech_count=$(echo "$json" | jq -r '.technology_count' 2>/dev/null)
	provider_count=$(echo "$json" | jq -r '.provider_count' 2>/dev/null)
	scan_time=$(echo "$json" | jq -r '.scan_time' 2>/dev/null)

	echo ""
	echo -e "${CYAN}=== Tech Stack: ${domain} ===${NC}"
	echo -e "URL: ${url}"
	echo -e "Scanned: ${scan_time} | Providers: ${provider_count} | Technologies: ${tech_count}"
	echo ""

	# Print by category
	echo "$json" | jq -r '.categories[] | "\(.category)|\(.count)"' 2>/dev/null | while IFS='|' read -r category count; do
		echo -e "${GREEN}${category}${NC} (${count}):"

		echo "$json" | jq -r --arg cat "$category" '
            .technologies[] | select(.category == $cat) |
            "  \(.name)\t\(.version // "-")\t\(.confidence * 100 | round)%\t[\(.detected_by | join(", "))]"
        ' 2>/dev/null | while IFS= read -r line; do
			echo -e "$line"
		done

		echo ""
	done

	return 0
}

# Format merged results as markdown
format_markdown() {
	local json="$1"

	local url domain tech_count provider_count scan_time
	url=$(echo "$json" | jq -r '.url' 2>/dev/null)
	domain=$(echo "$json" | jq -r '.domain' 2>/dev/null)
	tech_count=$(echo "$json" | jq -r '.technology_count' 2>/dev/null)
	provider_count=$(echo "$json" | jq -r '.provider_count' 2>/dev/null)
	scan_time=$(echo "$json" | jq -r '.scan_time' 2>/dev/null)

	echo "# Tech Stack Report: ${domain}"
	echo ""
	echo "- **URL**: ${url}"
	echo "- **Scanned**: ${scan_time}"
	echo "- **Providers**: ${provider_count}"
	echo "- **Technologies detected**: ${tech_count}"
	echo ""

	echo "## Technologies by Category"
	echo ""

	echo "$json" | jq -r '.categories[] | "### \(.category) (\(.count))\n"' 2>/dev/null | while IFS= read -r line; do
		echo "$line"
	done

	echo "| Technology | Version | Confidence | Detected By |"
	echo "|------------|---------|------------|-------------|"

	echo "$json" | jq -r '
        .technologies[] |
        "| \(.name) | \(.version // "-") | \(.confidence * 100 | round)% | \(.detected_by | join(", ")) |"
    ' 2>/dev/null

	echo ""
	echo "---"
	echo "*Generated by tech-stack-helper.sh v${VERSION}*"

	return 0
}

# =============================================================================
# Reverse Lookup Result Formatting
# =============================================================================

# Format reverse lookup results as terminal table
format_reverse_table() {
	local json="$1"

	local technology total_count scan_time note
	technology=$(echo "$json" | jq -r '.technology' 2>/dev/null)
	total_count=$(echo "$json" | jq -r '.total_count' 2>/dev/null)
	scan_time=$(echo "$json" | jq -r '.scan_time' 2>/dev/null)
	note=$(echo "$json" | jq -r '.note // empty' 2>/dev/null)

	echo ""
	echo -e "${CYAN}=== Reverse Lookup: ${technology} ===${NC}"
	echo -e "Scanned: ${scan_time} | Sites found: ${total_count}"

	if [[ -n "$note" ]]; then
		echo ""
		echo -e "${YELLOW}Note:${NC} ${note}"
	fi

	if [[ "$total_count" != "0" ]]; then
		echo ""
		echo "$json" | jq -r '.sites[] | "  \(.url)\t\(.traffic_tier // "-")\t\(.region // "-")"' 2>/dev/null
	fi

	echo ""
	return 0
}

# Format reverse lookup results as markdown
format_reverse_markdown() {
	local json="$1"

	local technology total_count scan_time note
	technology=$(echo "$json" | jq -r '.technology' 2>/dev/null)
	total_count=$(echo "$json" | jq -r '.total_count' 2>/dev/null)
	scan_time=$(echo "$json" | jq -r '.scan_time' 2>/dev/null)
	note=$(echo "$json" | jq -r '.note // empty' 2>/dev/null)

	echo "# Reverse Lookup: ${technology}"
	echo ""
	echo "- **Scanned**: ${scan_time}"
	echo "- **Sites found**: ${total_count}"

	if [[ -n "$note" ]]; then
		echo ""
		echo "> ${note}"
	fi

	if [[ "$total_count" != "0" ]]; then
		echo ""
		echo "| URL | Traffic | Region |"
		echo "|-----|---------|--------|"
		echo "$json" | jq -r '.sites[] | "| \(.url) | \(.traffic_tier // "-") | \(.region // "-") |"' 2>/dev/null
	fi

	echo ""
	echo "---"
	echo "*Generated by tech-stack-helper.sh v${VERSION}*"

	return 0
}

# =============================================================================
# Output Router
# =============================================================================

# Output results in the requested format
output_results() {
	local json="$1"
	local format="$2"

	# Detect result type (lookup vs reverse)
	local is_reverse="false"
	if echo "$json" | jq -e '.technology' &>/dev/null; then
		is_reverse="true"
	fi

	case "$format" in
	json)
		echo "$json" | jq '.' 2>/dev/null || echo "$json"
		;;
	markdown)
		if [[ "$is_reverse" == "true" ]]; then
			format_reverse_markdown "$json"
		else
			format_markdown "$json"
		fi
		;;
	table | *)
		if [[ "$is_reverse" == "true" ]]; then
			format_reverse_table "$json"
		else
			format_table "$json"
		fi
		;;
	esac

	return 0
}
