#!/bin/sh
# `mak` - launch the MAK IDE from anywhere, the way `claude` does.
#
# WHY A SCRIPT AND NOT A CONSOLE ENTRY POINT
#
# pyproject declares `mak` under [project.scripts], and that is the right thing
# for someone who installs this from a wheel - `pip install maku` or `uv tool
# install maku`. It is the WRONG thing for the person developing it: a console
# script is generated at
# install time, so it pins whatever the package looked like then, and every
# edit needs a reinstall before it can be run.
#
# This launcher resolves to the checkout instead, and the checkout's venv holds
# `site-packages/maku_tui` as a SYMLINK INTO `src/`. So there is nothing to
# rebuild and nothing to reinstall: a change to the source is live the next
# time `mak` starts. That is a deliberate property, not an accident - see
# `--doctor` below for the reason the symlink exists at all.
#
# It runs in the user's own directory, so `mak` in a project finds that
# project's maku.toml by searching upward, exactly like `git`.

set -eu

# Resolve this script's own path through however many symlinks put it on PATH.
# macOS `readlink` has no -f, so this walks them by hand.
src=$0
while [ -L "$src" ]; do
    dir=$(cd -P "$(dirname "$src")" && pwd)
    src=$(readlink "$src")
    case $src in
        /*) ;;
        *) src=$dir/$src ;;
    esac
done
HERE=$(cd -P "$(dirname "$src")" && pwd)
ROOT=$(cd -P "$HERE/.." && pwd)
PY=$ROOT/.venv/bin/python

die() { printf '%s\n' "mak: $*" >&2; exit 1; }

[ -x "$PY" ] || die "no interpreter at $PY.
    The checkout this launcher points at has no virtualenv. Create one:
        cd $ROOT && python3 -m venv .venv && .venv/bin/pip install -e ."

# THE FAILURE THIS TREE ACTUALLY HAS, CHECKED BEFORE IT CAN LOOK LIKE ANYTHING
# ELSE. Every .pth file under ~/Desktop here acquires the macOS UF_HIDDEN flag,
# and Python 3.13's site.addpackage SKIPS hidden .pth files - so an editable
# install reports as installed by pip and is inert at import. The symptom is
# "No module named maku_tui" from a venv that pip says is fine, which reads as
# a broken package and is a filesystem flag. `--doctor` says so out loud.
if ! "$PY" -c 'import maku_tui' 2>/dev/null; then
    die "the venv at $ROOT/.venv cannot import maku_tui.
    On this tree that is almost always the hidden-.pth failure, not a broken
    install: run 'mak --doctor' for the diagnosis and the one-line fix."
fi

case ${1-} in
    --doctor) shift; exec "$PY" -m maku_tui.doctor "$@" ;;
    --where)  printf '%s\n' "$ROOT"; exit 0 ;;
esac

exec "$PY" -m maku_tui "$@"
