#!/bin/bash
#
# Ledger API Service
# ==================
# Starts the FastAPI ledger service
#
# Usage:
#   ledger-api              Start on default port (8080)
#   ledger-api --port 8081  Start on custom port
#   ledger-api --no-auth    Disable authentication
#

set -euo pipefail

LEDGER_DIR="/opt/agent-governance/ledger"
VENV_DIR="${LEDGER_DIR}/.venv"

# Parse arguments
PORT="${LEDGER_API_PORT:-8080}"
AUTH="true"

while [[ $# -gt 0 ]]; do
    case $1 in
        --port)
            PORT="$2"
            shift 2
            ;;
        --no-auth)
            AUTH="false"
            shift
            ;;
        --help|-h)
            cat << 'EOF'
Ledger API Service
==================

Usage:
  ledger-api              Start on default port (8080)
  ledger-api --port 8081  Start on custom port
  ledger-api --no-auth    Disable Vault authentication

Environment Variables:
  LEDGER_API_PORT   Port to listen on (default: 8080)
  LEDGER_API_AUTH   Require Vault auth (default: true)
  VAULT_ADDR        Vault address (default: https://127.0.0.1:8200)

Endpoints:
  GET  /health      Health check
  GET  /docs        Swagger documentation
  GET  /agents      List agents
  GET  /violations  List violations
  GET  /promotions  List promotions
  GET  /stats       Overall statistics
EOF
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Create venv if needed
if [[ ! -d "${VENV_DIR}" ]]; then
    echo "Creating virtual environment..."
    python3 -m venv "${VENV_DIR}" 2>/dev/null || {
        echo "Installing dependencies globally..."
        pip3 install -q fastapi uvicorn pydantic
    }
fi

# Activate venv if it exists
if [[ -d "${VENV_DIR}" ]]; then
    source "${VENV_DIR}/bin/activate"

    # Install dependencies if needed
    if ! python3 -c "import fastapi" 2>/dev/null; then
        echo "Installing dependencies..."
        pip install -q -r "${LEDGER_DIR}/requirements.txt"
    fi
fi

# Export config
export LEDGER_API_PORT="${PORT}"
export LEDGER_API_AUTH="${AUTH}"

# Run API
exec python3 "${LEDGER_DIR}/api.py"
