#!/bin/bash

# --- CONFIGURATION ---

# Dimensions (Millimeters)
# Set the desired width in mm (e.g. 55.15). 
# Leave as "0" to keep the original size from the SVG.
TARGET_WIDTH_MM="45.08"

# Thickness of the 3D model in mm
THICKNESS_MM="0.1"

# Print resolution
# DPI based on the 3D printer resolution (e.g. 1494 for Anycubic Photon Mono 4)
EXPORT_DPI=1494

# Check for at least one input file
if [ "$#" -lt 1 ]; then
  echo "Error: No input files provided."
  echo "Usage: ./svg2stl.sh <file1.svg> [file2.svg ...]"
  exit 1
fi

# Loop over all input files
for INPUT in "$@"; do
  INPUT_FILE="$(readlink -f "$INPUT")"

  echo "Processing: $INPUT_FILE"

  # Setup Absolute Paths
  WORK_DIR="$(dirname "$INPUT_FILE")"
  BASENAME="$(basename "$INPUT_FILE" .svg)"
  TEMP_SVG="$WORK_DIR/${BASENAME}_temp_processed.svg"
  OUTPUT_STL="$WORK_DIR/$BASENAME.stl"

  # Inkscape Processing
  # Note: We do NOT resize here. We export high-res geometry and resize in Blender.
  ACTIONS="select-by-element:text;delete;select-all;object-stroke-to-path;path-union;export-plain-svg;export-filename:$TEMP_SVG;export-do"
  INK_ARGS="--export-dpi=$EXPORT_DPI --actions=$ACTIONS"

  echo "------------------------------------------------"
  echo "Step 1: Inkscape Processing"
  echo "Input: $INPUT_FILE"
  echo "------------------------------------------------"

  inkscape "$INPUT_FILE" $INK_ARGS

  if [ ! -f "$TEMP_SVG" ]; then
    echo "ERROR: Inkscape failed to create the temp file."
    exit 1
  fi

  echo "------------------------------------------------"
  echo "Step 2: Blender Processing"
  echo "Target Width:     ${TARGET_WIDTH_MM} mm"
  echo "Target Thickness: ${THICKNESS_MM} mm"
  echo "------------------------------------------------"

  # Pass Width and Thickness to Python
  blender --background --python pcb_to_stl.py -- "$TEMP_SVG" "$OUTPUT_STL" "$THICKNESS_MM" "$TARGET_WIDTH_MM"

  # Cleanup
  rm "$TEMP_SVG"
  echo "Done! Saved to $OUTPUT_STL"
  # ---------------------
done