#!/bin/bash
#
# Invoice Navigator CLI
# Validate e-invoices from the command line
#
# Installation:
#   curl -fsSL https://www.invoicenavigator.eu/cli/invoice-navigator.sh -o invoice-navigator
#   chmod +x invoice-navigator
#   mv invoice-navigator /usr/local/bin/
#
# Usage:
#   invoice-navigator validate invoice.xml
#   invoice-navigator validate invoices/*.xml
#   invoice-navigator verify ep_abc123
#   invoice-navigator test-key
#
# Environment:
#   INVOICE_NAV_API_KEY - Your API key (required for most commands)
#
# Get your API key: https://www.invoicenavigator.eu/signup?redirect=/dashboard/api

set -e

VERSION="1.0.0"
API_BASE="https://api.invoicenavigator.eu/v1"
WEB_BASE="https://www.invoicenavigator.eu"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Print functions
info() { echo -e "${BLUE}ℹ${NC} $1"; }
success() { echo -e "${GREEN}✓${NC} $1"; }
warning() { echo -e "${YELLOW}⚠${NC} $1"; }
error() { echo -e "${RED}✗${NC} $1"; }

# Check dependencies
check_deps() {
    for cmd in curl jq; do
        if ! command -v $cmd &> /dev/null; then
            error "Required dependency '$cmd' is not installed"
            exit 1
        fi
    done
}

# Get a test API key
cmd_test_key() {
    info "Getting instant test key..."

    RESPONSE=$(curl -s -X POST "$WEB_BASE/api/developers/instant-key" \
        -H "Content-Type: application/json" \
        -d '{}')

    if echo "$RESPONSE" | jq -e '.apiKey' > /dev/null 2>&1; then
        API_KEY=$(echo "$RESPONSE" | jq -r '.apiKey')
        EXPIRES=$(echo "$RESPONSE" | jq -r '.expiresAt')
        REQUESTS=$(echo "$RESPONSE" | jq -r '.requestsRemaining')

        echo ""
        success "Test key created!"
        echo ""
        echo "  API Key: $API_KEY"
        echo "  Expires: $EXPIRES"
        echo "  Requests remaining: $REQUESTS"
        echo ""
        echo "To use this key:"
        echo "  export INVOICE_NAV_API_KEY=$API_KEY"
        echo ""
        warning "This is a test key (10 requests, 1 hour). Sign up for unlimited access."
        echo "  $WEB_BASE/signup?redirect=/dashboard/api"
    else
        ERROR=$(echo "$RESPONSE" | jq -r '.error // "Unknown error"')
        error "Failed to get test key: $ERROR"
        exit 1
    fi
}

# Validate invoice(s)
cmd_validate() {
    if [ -z "$INVOICE_NAV_API_KEY" ]; then
        error "INVOICE_NAV_API_KEY environment variable is not set"
        echo ""
        echo "Get a test key:    invoice-navigator test-key"
        echo "Or sign up:        $WEB_BASE/signup?redirect=/dashboard/api"
        exit 1
    fi

    if [ $# -eq 0 ]; then
        error "No invoice files specified"
        echo "Usage: invoice-navigator validate <file.xml> [file2.xml ...]"
        exit 1
    fi

    TOTAL=0
    PASSED=0
    FAILED=0

    for FILE in "$@"; do
        if [ ! -f "$FILE" ]; then
            warning "File not found: $FILE"
            continue
        fi

        TOTAL=$((TOTAL + 1))
        info "Validating: $FILE"

        # Read and escape the XML
        XML_CONTENT=$(cat "$FILE" | jq -Rs .)

        # Call the API
        RESPONSE=$(curl -s -X POST "$API_BASE/validate" \
            -H "Authorization: Bearer $INVOICE_NAV_API_KEY" \
            -H "Content-Type: application/json" \
            -d "{\"xml\": $XML_CONTENT}")

        # Check for API errors
        if echo "$RESPONSE" | jq -e '.error' > /dev/null 2>&1; then
            ERROR=$(echo "$RESPONSE" | jq -r '.error')
            error "$FILE: API Error - $ERROR"
            FAILED=$((FAILED + 1))
            continue
        fi

        # Parse results
        IS_VALID=$(echo "$RESPONSE" | jq -r '.valid // false')
        FORMAT=$(echo "$RESPONSE" | jq -r '.format.type // "unknown"')
        PROFILE=$(echo "$RESPONSE" | jq -r '.profile.name // "unknown"')
        ERROR_COUNT=$(echo "$RESPONSE" | jq -r '.errors | length // 0')
        WARNING_COUNT=$(echo "$RESPONSE" | jq -r '.warnings | length // 0')

        if [ "$IS_VALID" = "true" ]; then
            success "$FILE: Valid ($FORMAT, $PROFILE)"
            [ "$WARNING_COUNT" -gt 0 ] && warning "  $WARNING_COUNT warning(s)"
            PASSED=$((PASSED + 1))
        else
            error "$FILE: Invalid ($ERROR_COUNT error(s))"
            echo "$RESPONSE" | jq -r '.errors[]? | "  [\(.code)] \(.message)"'
            FAILED=$((FAILED + 1))
        fi
    done

    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "Summary: $PASSED/$TOTAL valid"
    [ $FAILED -gt 0 ] && error "$FAILED invoice(s) failed validation"
    [ $FAILED -eq 0 ] && success "All invoices valid!"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

    [ $FAILED -gt 0 ] && exit 1
    exit 0
}

# Verify an Evidence Pack
cmd_verify() {
    if [ -z "$1" ]; then
        error "No certificate ID specified"
        echo "Usage: invoice-navigator verify <certificate_id>"
        exit 1
    fi

    info "Verifying certificate: $1"

    RESPONSE=$(curl -s "$API_BASE/verify/$1")

    if echo "$RESPONSE" | jq -e '.error' > /dev/null 2>&1; then
        ERROR=$(echo "$RESPONSE" | jq -r '.error')
        error "Verification failed: $ERROR"
        exit 1
    fi

    IS_VALID=$(echo "$RESPONSE" | jq -r '.valid // false')
    EXPIRES=$(echo "$RESPONSE" | jq -r '.expiresAt // "unknown"')

    if [ "$IS_VALID" = "true" ]; then
        success "Certificate is valid!"
        echo ""
        echo "$RESPONSE" | jq -r '"  Invoice: \(.invoice.number // "N/A")"'
        echo "$RESPONSE" | jq -r '"  Created: \(.createdAt)"'
        echo "  Expires: $EXPIRES"
        echo ""
        echo "View online: $WEB_BASE/verify/$1"
    else
        error "Certificate is invalid or expired"
        exit 1
    fi
}

# Show help
cmd_help() {
    echo "Invoice Navigator CLI v$VERSION"
    echo ""
    echo "Usage: invoice-navigator <command> [options]"
    echo ""
    echo "Commands:"
    echo "  validate <file.xml> [files...]   Validate e-invoice XML files"
    echo "  verify <certificate_id>          Verify an Evidence Pack certificate"
    echo "  test-key                         Get an instant test API key"
    echo "  help                             Show this help message"
    echo "  version                          Show version"
    echo ""
    echo "Environment:"
    echo "  INVOICE_NAV_API_KEY              Your API key (required for validation)"
    echo ""
    echo "Examples:"
    echo "  invoice-navigator test-key"
    echo "  export INVOICE_NAV_API_KEY=sk_test_xxx"
    echo "  invoice-navigator validate invoice.xml"
    echo "  invoice-navigator validate invoices/*.xml"
    echo "  invoice-navigator verify ep_abc123"
    echo ""
    echo "Documentation: $WEB_BASE/developers"
    echo "Get API Key:   $WEB_BASE/signup?redirect=/dashboard/api"
}

# Main
check_deps

case "${1:-help}" in
    validate)
        shift
        cmd_validate "$@"
        ;;
    verify)
        shift
        cmd_verify "$@"
        ;;
    test-key|testkey)
        cmd_test_key
        ;;
    version|--version|-v)
        echo "invoice-navigator v$VERSION"
        ;;
    help|--help|-h|*)
        cmd_help
        ;;
esac
