#!/usr/bin/env bash
#
# Toggle propresenter/parser between remote VCS and local path repository.
#
# Usage:
#   ./use_local_pp_lib.sh <path>   — Switch to local checkout (symlinked)
#   ./use_local_pp_lib.sh --remote — Switch back to remote VCS
#
# Examples:
#   ./use_local_pp_lib.sh ../propresenter
#   ./use_local_pp_lib.sh /absolute/path/to/propresenter-php
#   ./use_local_pp_lib.sh --remote
#
set -euo pipefail

COMPOSER_FILE="composer.json"

if [[ ! -f "$COMPOSER_FILE" ]]; then
    echo "Error: $COMPOSER_FILE nicht gefunden. Bitte im Projektverzeichnis ausfuehren." >&2
    exit 1
fi

if [[ $# -lt 1 ]]; then
    echo "Usage: $0 <local-path> | --remote" >&2
    echo "" >&2
    echo "  <local-path>  Pfad zum lokalen propresenter-php Checkout" >&2
    echo "  --remote      Zurueck zum Remote-Repository wechseln" >&2
    exit 1
fi

switch_to_remote() {
    echo "Wechsle zu Remote-VCS Repository..."

    php -r '
        $json = json_decode(file_get_contents("composer.json"), true);
        $json["repositories"] = array_values(array_filter($json["repositories"], function($r) {
            return ($r["type"] ?? "") !== "path";
        }));
        file_put_contents("composer.json", json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n");
    '

    if [[ -L "vendor/propresenter/parser" ]] || [[ -d "vendor/propresenter/parser" ]]; then
        rm -rf vendor/propresenter/parser
    fi

    composer update propresenter/parser
    echo ""
    echo "propresenter/parser wird jetzt vom Remote-Repository geladen."
}

switch_to_local() {
    local LOCAL_PATH="$1"

    if [[ "$LOCAL_PATH" != /* ]]; then
        LOCAL_PATH="$(cd "$(dirname "$LOCAL_PATH")" && pwd)/$(basename "$LOCAL_PATH")"
    fi

    if [[ ! -f "$LOCAL_PATH/composer.json" ]]; then
        echo "Error: Keine composer.json in $LOCAL_PATH gefunden." >&2
        echo "Bitte den Pfad zum propresenter-php Root-Verzeichnis angeben." >&2
        exit 1
    fi

    local PKG_NAME
    PKG_NAME=$(php -r "echo json_decode(file_get_contents('$LOCAL_PATH/composer.json'), true)['name'] ?? '';")
    if [[ "$PKG_NAME" != "propresenter/parser" ]]; then
        echo "Error: Package in $LOCAL_PATH ist '$PKG_NAME', erwartet 'propresenter/parser'." >&2
        exit 1
    fi

    local REL_PATH
    REL_PATH=$(python3 -c "import os; print(os.path.relpath('$LOCAL_PATH', '$(pwd)'))")

    echo "Wechsle zu lokalem Checkout: $REL_PATH"

    php -r '
        $relPath = $argv[1];
        $json = json_decode(file_get_contents("composer.json"), true);
        $json["repositories"] = array_values(array_filter($json["repositories"], function($r) {
            return ($r["type"] ?? "") !== "path";
        }));
        array_unshift($json["repositories"], [
            "type" => "path",
            "url" => $relPath,
            "options" => ["symlink" => true],
        ]);

        file_put_contents("composer.json", json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n");
    ' -- "$REL_PATH"

    if [[ -L "vendor/propresenter/parser" ]] || [[ -d "vendor/propresenter/parser" ]]; then
        rm -rf vendor/propresenter/parser
    fi

    composer update propresenter/parser
    echo ""
    echo "propresenter/parser ist jetzt mit $REL_PATH verlinkt (Symlink)."
    echo "Aenderungen in $REL_PATH sind sofort verfuegbar."
}

case "$1" in
    --remote|-r)
        switch_to_remote
        ;;
    --help|-h)
        echo "Usage: $0 <local-path> | --remote"
        echo ""
        echo "  <local-path>  Pfad zum lokalen propresenter-php Checkout"
        echo "  --remote      Zurueck zum Remote-Repository wechseln"
        ;;
    *)
        switch_to_local "$1"
        ;;
esac
