#!/usr/bin/bash
#
# tidesi-cli — terminal frontend for the shared provider backend.
#
# Renders the same contract the Plasma widget and the Quickshell panel render,
# as a table or — with --compact — as a single status-bar line. This is a thin
# launcher; the rendering lives in ../tidesi/render.py and the argument
# handling in ../tidesi/cli.py. See docs/provider-contract.md.
#
#   tidesi-cli                        table of every enabled provider
#   tidesi-cli --provider claude      one provider
#   tidesi-cli --compact              one line, for waybar/tmux/i3blocks
#   get-ai-usage --all | tidesi-cli   render an envelope, no network
#
set -u

# Resolve through symlinks before locating the package: BASH_SOURCE reports the
# link rather than its target, and this frontend in particular is meant to be
# linked into ~/.local/bin. `readlink -f` is not portable, so walk the chain by
# hand.
#
# This repeats the loop in get-ai-usage instead of sharing it via
# python-interp.sh, and has to: resolving the path is precisely what lets a
# launcher find that sibling file, so the resolution cannot live inside it.
_src="${BASH_SOURCE[0]}"
while [ -L "$_src" ]; do
    _link_dir="$(cd "$(dirname "$_src")" && pwd)"
    _src="$(readlink "$_src")"
    case "$_src" in
        /*) ;;
        *) _src="$_link_dir/$_src" ;;
    esac
done
_SH_DIR="$(cd "$(dirname "$_src")" && pwd)"

# Shared interpreter resolution — sets $PY, empty when no Python 3 exists.
. "$_SH_DIR/python-interp.sh"

if ! py_resolve; then
    # Unlike get-ai-usage, this has no frontend to keep alive: a person is
    # reading the output, so say what is wrong instead of emitting an error
    # envelope they would have to decode.
    printf 'tidesi-cli: no Python 3 interpreter found (tried $PYTHON3, python3, python3.x, python)\n' >&2
    exit 1
fi

# The tidesi package lives one directory up (tools/tidesi; this is tools/sh).
PKG_TOOLS="$(cd "$_SH_DIR/.." && pwd)"
export PYTHONPATH="$PKG_TOOLS${PYTHONPATH:+:$PYTHONPATH}"

# -B: never write __pycache__ into an installed plasmoid.
exec "$PY" -B -m tidesi.cli "$@"
