#!/bin/sh
# Desktop launcher for the native iced client.
#
# Resolution order:
#   1. explicit client arguments are passed through unchanged;
#   2. DSH_NATIVE_URL (legacy DSH_ICED_URL) starts the client against that Host URL;
#   3. DSH_NATIVE_REPO (legacy DSH_ICED_REPO), the current directory ancestry, or a conventional
#      checkout location is used to start `dsh web` through `--launch`;
#   4. otherwise the client opens its setup screen: it checks whether this machine
#      can run DeepSeek Harness, asks for a source checkout or `npx`, and only then
#      offers the Host URL and relay (mobile access) configuration.
set -eu

APP=DSHNative

if [ "$#" -gt 0 ]; then
    exec "$APP" "$@"
fi

# The client only ships an English and a Simplified Chinese locale, so use the
# session locale as the default when the user did not pass --zh themselves.
locale=${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}
if [ "${locale%%_*}" = zh ]; then
    set -- --zh
fi

url=${DSH_NATIVE_URL:-${DSH_ICED_URL:-}}
if [ -n "$url" ]; then
    exec "$APP" --url "$url" "$@"
fi

repo=
explicit_repo=${DSH_NATIVE_REPO:-${DSH_ICED_REPO:-}}
if [ -n "$explicit_repo" ] &&
    [ -f "$explicit_repo/pnpm-workspace.yaml" ] &&
    [ -f "$explicit_repo/apps/cli/package.json" ]; then
    repo=$explicit_repo
fi

if [ -z "$repo" ]; then
    directory=$(pwd)
    while :; do
        if [ -f "$directory/pnpm-workspace.yaml" ] &&
            [ -f "$directory/apps/cli/package.json" ]; then
            repo=$directory
            break
        fi
        [ "$directory" = / ] && break
        directory=$(dirname "$directory")
    done
fi

if [ -z "$repo" ]; then
    for candidate in \
        "${HOME:-/nonexistent}/dev_work/deepseek-harness" \
        "${HOME:-/nonexistent}/deepseek-harness" \
        /opt/deepseek-harness \
        /usr/share/deepseek-harness; do
        if [ -f "$candidate/pnpm-workspace.yaml" ] &&
            [ -f "$candidate/apps/cli/package.json" ]; then
            repo=$candidate
            break
        fi
    done
fi

if [ -z "$repo" ]; then
    # No checkout: the setup screen can still start the published package with
    # `npx @deepseek-ai/dsh web`, so keep the plain launch inside the guide and
    # let the user pick the method there.
    exec "$APP" "$@"
fi

export PATH="$repo/node_modules/.bin:$repo/apps/cli/node_modules/.bin:$PATH"
cd "$repo"
exec "$APP" --launch "$@"
