#!/usr/bin/env bash
# Generate study card from conversation, build PDF, and optionally print
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TUFTE_PRESS_REPO="${TUFTE_PRESS_REPO:-$HOME/proj/tufte-press}"

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

log_info() {
    echo -e "${GREEN}ℹ${NC} $1" >&2
}

log_error() {
    echo -e "${RED}✗${NC} $1" >&2
}

log_warning() {
    echo -e "${YELLOW}⚠${NC} $1" >&2
}

log_step() {
    echo -e "${BLUE}▸${NC} $1" >&2
}

show_usage() {
    cat <<EOF
Usage: $0 <json_file> [--build] [--print] [--printer <name>] [--copies <n>]

Arguments:
  json_file       Path to study card JSON file
  --build         Build PDF from JSON (default: false)
  --print         Send PDF to printer (requires --build)
  --printer       Printer name (default: system default)
  --copies        Number of copies (default: 1)
  --duplex        Enable duplex printing (long-edge)

Examples:
  # Validate JSON only
  $0 my-card.json

  # Generate and build PDF
  $0 my-card.json --build

  # Build and print 2 copies duplex
  $0 my-card.json --build --print --copies 2 --duplex

Environment:
  TUFTE_PRESS_REPO   Path to tufte-press repo (default: ~/proj/tufte-press)
EOF
    exit 1
}

validate_tufte_repo() {
    if [[ ! -d "$TUFTE_PRESS_REPO" ]]; then
        log_error "tufte-press repository not found at: $TUFTE_PRESS_REPO"
        log_error "Set TUFTE_PRESS_REPO environment variable or clone the repo"
        exit 1
    fi

    if [[ ! -f "$TUFTE_PRESS_REPO/scripts/card-build.sh" ]]; then
        log_error "card-build.sh not found in tufte-press repository"
        exit 1
    fi

    if [[ ! -f "$TUFTE_PRESS_REPO/scripts/metadata-validate.sh" ]]; then
        log_error "metadata-validate.sh not found in tufte-press repository"
        exit 1
    fi
}

validate_json() {
    local json_file="$1"
    
    log_step "Validating JSON metadata..."
    
    if ! "$TUFTE_PRESS_REPO/scripts/metadata-validate.sh" "$json_file"; then
        log_error "JSON validation failed"
        return 1
    fi
    
    log_info "Validation passed"
    return 0
}

build_pdf() {
    local json_file="$1"
    local output_pdf="$2"
    
    log_step "Building PDF from JSON..."
    
    # Use build-card wrapper which handles Nix shell entry
    local build_script="$SCRIPT_DIR/build-card.sh"
    if [[ ! -f "$build_script" ]]; then
        # Fallback to direct call (assumes already in dev environment)
        build_script="$TUFTE_PRESS_REPO/scripts/card-build.sh"
    fi
    
    if ! "$build_script" "$json_file" --output "$output_pdf"; then
        log_error "PDF build failed"
        return 1
    fi
    
    if [[ ! -f "$output_pdf" ]]; then
        log_error "PDF was not generated at: $output_pdf"
        return 1
    fi
    
    log_info "PDF generated: $output_pdf"
    return 0
}

print_pdf() {
    local pdf_file="$1"
    local printer="${2:-}"
    local copies="${3:-1}"
    local duplex="${4:-false}"
    
    log_step "Sending PDF to printer..."
    
    # Check if lp is available
    if ! command -v lp &> /dev/null; then
        log_error "lp command not found - printing not available"
        return 1
    fi
    
    # Build lp command
    local lp_args=("-n" "$copies")
    
    if [[ -n "$printer" ]]; then
        lp_args+=("-d" "$printer")
    fi
    
    if [[ "$duplex" == "true" ]]; then
        lp_args+=("-o" "sides=two-sided-long-edge")
    fi
    
    lp_args+=("$pdf_file")
    
    log_info "Print command: lp ${lp_args[*]}"
    
    if ! lp "${lp_args[@]}"; then
        log_error "Print failed"
        return 1
    fi
    
    log_info "Print job submitted successfully"
    
    # Show print queue status
    if command -v lpstat &> /dev/null; then
        log_info "Print queue:"
        lpstat -o 2>/dev/null || true
    fi
    
    return 0
}

main() {
    local json_file=""
    local do_build=false
    local do_print=false
    local printer=""
    local copies=1
    local duplex=false
    
    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            --build)
                do_build=true
                shift
                ;;
            --print)
                do_print=true
                shift
                ;;
            --printer)
                printer="$2"
                shift 2
                ;;
            --copies)
                copies="$2"
                shift 2
                ;;
            --duplex)
                duplex=true
                shift
                ;;
            -h|--help)
                show_usage
                ;;
            -*)
                log_error "Unknown option: $1"
                show_usage
                ;;
            *)
                if [[ -z "$json_file" ]]; then
                    json_file="$1"
                else
                    log_error "Multiple input files specified"
                    show_usage
                fi
                shift
                ;;
        esac
    done
    
    if [[ -z "$json_file" ]]; then
        log_error "No input JSON file specified"
        show_usage
    fi
    
    if [[ ! -f "$json_file" ]]; then
        log_error "Input file not found: $json_file"
        exit 1
    fi
    
    if [[ "$do_print" == "true" && "$do_build" == "false" ]]; then
        log_error "--print requires --build"
        exit 1
    fi
    
    echo "📄 Tufte Press Study Card Workflow"
    echo "===================================="
    echo ""
    
    # Validate tufte-press repo
    validate_tufte_repo
    
    # Always validate JSON
    if ! validate_json "$json_file"; then
        exit 1
    fi
    
    # Build PDF if requested
    if [[ "$do_build" == "true" ]]; then
        local base_name
        base_name="$(basename "$json_file" .json)"
        local output_pdf="${json_file%.json}.pdf"
        
        if ! build_pdf "$json_file" "$output_pdf"; then
            exit 1
        fi
        
        # Print if requested
        if [[ "$do_print" == "true" ]]; then
            if ! print_pdf "$output_pdf" "$printer" "$copies" "$duplex"; then
                exit 1
            fi
        fi
        
        echo ""
        echo -e "${GREEN}✓${NC} Workflow complete!"
        echo "  JSON: $json_file"
        echo "  PDF:  $output_pdf"
        
        if [[ "$do_print" == "true" ]]; then
            echo "  Print: ${copies} copies submitted"
        fi
    else
        echo ""
        echo -e "${GREEN}✓${NC} JSON validation complete!"
        echo "  Use --build to generate PDF"
        echo "  Use --build --print to generate and print"
    fi
}

main "$@"
