#!/usr/bin/env bash
# Visualize an AIGER circuit as SVG using aigtodot + graphviz, or yosys.
#
# Usage: ./scripts/visualize.sh circuits/DRC.aag [output_dir] [method]
#
# Methods:
#   dot    - aigtodot + graphviz (default, requires aiger tools + graphviz)
#   yosys  - yosys show command (requires yosys + graphviz)

set -euo pipefail

AAG_FILE="${1:?Usage: $0 <circuit.aag> [output_dir] [dot|yosys]}"
OUTPUT_DIR="${2:-diagrams}"
METHOD="${3:-dot}"

BASENAME=$(basename "$AAG_FILE" .aag)
mkdir -p "$OUTPUT_DIR"

case "$METHOD" in
    dot)
        if ! command -v aigtodot &>/dev/null; then
            echo "Error: aigtodot not found."
            echo "Install AIGER tools: https://github.com/arminbiere/aiger"
            echo "  git clone https://github.com/arminbiere/aiger && cd aiger && ./configure.sh && make"
            exit 1
        fi
        if ! command -v dot &>/dev/null; then
            echo "Error: graphviz not found. Install with: brew install graphviz"
            exit 1
        fi
        echo "Generating DOT from AIGER..."
        aigtodot "$AAG_FILE" | dot -Tsvg -o "$OUTPUT_DIR/${BASENAME}.svg"
        echo "SVG written to: $OUTPUT_DIR/${BASENAME}.svg"

        # Also generate PNG for quick viewing
        aigtodot "$AAG_FILE" | dot -Tpng -o "$OUTPUT_DIR/${BASENAME}.png"
        echo "PNG written to: $OUTPUT_DIR/${BASENAME}.png"
        ;;

    yosys)
        if ! command -v yosys &>/dev/null; then
            echo "Error: yosys not found. Install with: brew install yosys"
            exit 1
        fi
        if ! command -v dot &>/dev/null; then
            echo "Error: graphviz not found. Install with: brew install graphviz"
            exit 1
        fi
        echo "Generating schematic with Yosys..."
        yosys -p "read_aiger $AAG_FILE; show -format svg -prefix $OUTPUT_DIR/${BASENAME}"
        echo "SVG written to: $OUTPUT_DIR/${BASENAME}.svg"
        ;;

    *)
        echo "Unknown method: $METHOD (use 'dot' or 'yosys')"
        exit 1
        ;;
esac

echo ""
echo "Open with: open $OUTPUT_DIR/${BASENAME}.svg"
