#!/bin/sh
#
# configure -- detect compiler and ncurses for DoomsDay 2026
#
# Usage:  ./configure [options]
#   --prefix=DIR        Installation prefix (default: /usr/local)
#   --cc=COMPILER       C compiler to use (default: auto-detect)
#   --with-ncurses=DIR  ncurses installation prefix
#   --help              Show this message
#

set -e

PREFIX=/usr/local
CC_OVERRIDE=""
NCURSES_DIR=""

for arg in "$@"; do
    case "$arg" in
        --prefix=*)    PREFIX="${arg#--prefix=}" ;;
        --cc=*)        CC_OVERRIDE="${arg#--cc=}" ;;
        --with-ncurses=*) NCURSES_DIR="${arg#--with-ncurses=}" ;;
        --help|-h)
            sed -n '3,9p' "$0"
            exit 0
            ;;
        *)
            echo "Unknown option: $arg"
            echo "Try: ./configure --help"
            exit 1
            ;;
    esac
done

echo "Configuring DoomsDay 2026..."
echo ""

# --- Detect OS ---
UNAME_S=$(uname -s)
echo "Operating system: $UNAME_S"

# --- Find C compiler ---
if [ -n "$CC_OVERRIDE" ]; then
    CC="$CC_OVERRIDE"
elif command -v cc >/dev/null 2>&1; then
    CC=cc
elif command -v gcc >/dev/null 2>&1; then
    CC=gcc
elif command -v clang >/dev/null 2>&1; then
    CC=clang
else
    echo "Error: no C compiler found. Install gcc or clang."
    exit 1
fi

# Verify it works
TMPF=$(mktemp /tmp/dd26_XXXXXX.c)
cat > "$TMPF" <<'TESTC'
#include <stdio.h>
int main(void) { return 0; }
TESTC
if ! $CC -o /dev/null "$TMPF" 2>/dev/null; then
    echo "Error: $CC cannot compile a simple program."
    rm -f "$TMPF"
    exit 1
fi
rm -f "$TMPF"
echo "C compiler:      $CC"

# --- Find ncurses ---
CURSES_CFLAGS=""
CURSES_LIBS=""
CURSES_FOUND=no

try_compile_curses() {
    _cflags="$1"
    _libs="$2"
    TMPF=$(mktemp /tmp/dd26_XXXXXX.c)
    cat > "$TMPF" <<'TESTC'
#include <curses.h>
int main(void) {
    initscr();
    endwin();
    return 0;
}
TESTC
    if $CC $_cflags -o /dev/null "$TMPF" $_libs 2>/dev/null; then
        rm -f "$TMPF"
        return 0
    fi
    rm -f "$TMPF"
    return 1
}

# Method 1: explicit --with-ncurses path
if [ -n "$NCURSES_DIR" ]; then
    echo "Checking --with-ncurses=$NCURSES_DIR..."
    cf="-I${NCURSES_DIR}/include"
    lf="-L${NCURSES_DIR}/lib -lncurses"
    if [ -d "${NCURSES_DIR}/include/ncurses" ]; then
        cf="-I${NCURSES_DIR}/include/ncurses -I${NCURSES_DIR}/include"
    fi
    if try_compile_curses "$cf" "$lf"; then
        CURSES_CFLAGS="$cf"
        CURSES_LIBS="$lf"
        CURSES_FOUND=yes
    fi
fi

# Method 2: pkg-config
if [ "$CURSES_FOUND" = "no" ] && command -v pkg-config >/dev/null 2>&1; then
    for pkg in ncurses ncursesw curses; do
        if pkg-config --exists "$pkg" 2>/dev/null; then
            cf=$(pkg-config --cflags "$pkg" 2>/dev/null)
            lf=$(pkg-config --libs "$pkg" 2>/dev/null)
            if try_compile_curses "$cf" "$lf"; then
                CURSES_CFLAGS="$cf"
                CURSES_LIBS="$lf"
                CURSES_FOUND=yes
                echo "ncurses:         found via pkg-config ($pkg)"
                break
            fi
        fi
    done
fi

# Method 3: common system paths
if [ "$CURSES_FOUND" = "no" ]; then
    SEARCH_PATHS="/usr /usr/local /opt/homebrew /opt/local"
    for dir in $SEARCH_PATHS; do
        if [ ! -d "$dir" ]; then continue; fi
        cf=""
        lf="-lncurses"
        if [ -f "$dir/include/ncurses.h" ] || [ -f "$dir/include/curses.h" ]; then
            if [ "$dir" != "/usr" ]; then
                cf="-I${dir}/include"
                lf="-L${dir}/lib -lncurses"
            fi
        elif [ -f "$dir/include/ncurses/ncurses.h" ]; then
            cf="-I${dir}/include/ncurses"
            if [ "$dir" != "/usr" ]; then
                cf="$cf -I${dir}/include"
                lf="-L${dir}/lib -lncurses"
            fi
        else
            continue
        fi
        if try_compile_curses "$cf" "$lf"; then
            CURSES_CFLAGS="$cf"
            CURSES_LIBS="$lf"
            CURSES_FOUND=yes
            echo "ncurses:         found in $dir"
            break
        fi
    done
fi

# Method 4: just try -lncurses bare
if [ "$CURSES_FOUND" = "no" ]; then
    if try_compile_curses "" "-lncurses"; then
        CURSES_LIBS="-lncurses"
        CURSES_FOUND=yes
        echo "ncurses:         found (system default)"
    fi
fi

if [ "$CURSES_FOUND" = "no" ]; then
    echo ""
    echo "Error: ncurses library not found."
    echo ""
    echo "Install it with:"
    echo "  macOS:   xcode-select --install"
    echo "  Debian:  sudo apt install libncurses-dev"
    echo "  Fedora:  sudo dnf install ncurses-devel"
    echo "  Arch:    sudo pacman -S ncurses"
    echo ""
    echo "Or specify the path:  ./configure --with-ncurses=/path/to/ncurses"
    exit 1
fi

# --- Check for math library ---
MATH_LIBS=""
TMPF=$(mktemp /tmp/dd26_XXXXXX.c)
cat > "$TMPF" <<'TESTC'
#include <math.h>
int main(void) { return (int)sqrt(2.0); }
TESTC
if $CC -o /dev/null "$TMPF" -lm 2>/dev/null; then
    MATH_LIBS="-lm"
elif $CC -o /dev/null "$TMPF" 2>/dev/null; then
    MATH_LIBS=""
else
    echo "Error: math library not found."
    rm -f "$TMPF"
    exit 1
fi
rm -f "$TMPF"

# --- Generate Makefile ---
cat > Makefile <<MAKEOF
# Generated by configure -- do not edit
CC = $CC
CFLAGS = -Wall -Wextra -O2 -std=c11 -D_XOPEN_SOURCE=700 $CURSES_CFLAGS
LDFLAGS = $CURSES_LIBS $MATH_LIBS

PREFIX = $PREFIX
SRCDIR = src
SRCS = \$(SRCDIR)/main.c \$(SRCDIR)/display.c \$(SRCDIR)/map.c \\
       \$(SRCDIR)/player.c \$(SRCDIR)/monster.c \$(SRCDIR)/item.c \\
       \$(SRCDIR)/combat.c \$(SRCDIR)/input.c \$(SRCDIR)/install.c \\
       \$(SRCDIR)/save.c \$(SRCDIR)/util.c

OBJS = \$(SRCS:.c=.o)
TARGET = doomsday2026

.PHONY: all clean install

all: \$(TARGET)

\$(TARGET): \$(OBJS)
	\$(CC) \$(OBJS) -o \$@ \$(LDFLAGS)

\$(SRCDIR)/%.o: \$(SRCDIR)/%.c \$(SRCDIR)/defs.h
	\$(CC) \$(CFLAGS) -c \$< -o \$@

clean:
	rm -f \$(OBJS) \$(TARGET)

install: \$(TARGET)
	install -d \$(PREFIX)/bin
	install -m 755 \$(TARGET) \$(PREFIX)/bin/\$(TARGET)
MAKEOF

echo ""
echo "Configuration complete."
echo ""
echo "  Compiler:  $CC"
echo "  CFLAGS:    -Wall -Wextra -O2 -std=c11 -D_XOPEN_SOURCE=700 $CURSES_CFLAGS"
echo "  LDFLAGS:   $CURSES_LIBS $MATH_LIBS"
echo "  Prefix:    $PREFIX"
echo ""
echo "Run 'make' to build."
