#!/bin/bash
#
# sase_git_commit — thin wrapper around `sase commit` that adds JSON logging.
#
# Usage: sase_git_commit [sase commit args...]
#
# All commit logic lives in CommitWorkflow and VCS providers;
# this script only adds structured logging and per-agent invocation evidence.

set -euo pipefail

LOG_FILE="${HOME}/.sase_git_commit.jsonl"
SCRIPT_START_EPOCH=$(date +%s)

# --- JSON logging --------------------------------------------------------- #

function jlog() {
  command -v jq &>/dev/null || return 0
  local event="$1"
  shift

  local jq_args=()
  local jq_pairs=""
  local i=0

  while [[ $# -gt 0 ]]; do
    local key="${1%%=*}"
    local val="${1#*=}"
    jq_args+=("--arg" "k${i}" "$key" "--arg" "v${i}" "$val")
    jq_pairs+=", (\$k${i}): \$v${i}"
    i=$((i + 1))
    shift
  done

  jq -c -n --arg ts "$(TZ=America/New_York date +%Y-%m-%dT%H:%M:%S%:z)" --arg event "$event" \
    "${jq_args[@]}" \
    "{timestamp: \$ts, event: \$event${jq_pairs}}" >>"${LOG_FILE}" 2>/dev/null
}

function write_invocation_marker() {
  [[ -n "${SASE_ARTIFACTS_DIR:-}" ]] || return 0

  local py="${PYTHON:-}"
  if [[ -z "${py}" ]]; then
    py="$(command -v python3 || command -v python || true)"
  fi
  if [[ -z "${py}" ]]; then
    jlog "commit_skill_marker_skipped" "reason=python_not_found"
    return 0
  fi

  "${py}" - "$@" <<'PY'
import json
import os
import sys
from datetime import datetime
from pathlib import Path

ALIASES = {
    "commit": "create_commit",
    "propose": "create_proposal",
    "pr": "create_pull_request",
}


def _canonical(method: str) -> str:
    return ALIASES.get(method, method)


def _parse_args(argv: list[str]) -> tuple[list[str], str, bool]:
    files: list[str] = []
    cli_method = ""
    resume = False
    i = 0
    while i < len(argv):
        arg = argv[i]
        if arg in ("-f", "--file"):
            if i + 1 < len(argv):
                files.append(argv[i + 1])
                i += 2
                continue
        elif arg.startswith("--file="):
            files.append(arg.split("=", 1)[1])
        elif arg in ("-t", "--type"):
            if i + 1 < len(argv):
                cli_method = argv[i + 1]
                i += 2
                continue
        elif arg.startswith("--type="):
            cli_method = arg.split("=", 1)[1]
        elif arg in ("-r", "--resume"):
            resume = True
        i += 1
    return files, cli_method, resume


artifacts_dir = os.environ["SASE_ARTIFACTS_DIR"]
argv = sys.argv[1:]
files, raw_cli_method, resume = _parse_args(argv)
raw_env_method = os.environ.get("SASE_COMMIT_METHOD", "")
cli_method = _canonical(raw_cli_method) if raw_cli_method else ""
env_method = _canonical(raw_env_method) if raw_env_method else ""
if resume:
    method = "resume"
    method_source = "resume"
elif cli_method:
    method = cli_method
    method_source = "cli"
elif env_method:
    method = env_method
    method_source = "env"
else:
    method = "create_commit"
    method_source = "default"

run_id = os.environ.get("SASE_AGENT_TIMESTAMP", "").strip()
if not run_id:
    run_id = Path(artifacts_dir).expanduser().resolve(strict=False).name

marker = {
    "schema_version": 1,
    "timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
    "run_id": run_id,
    "cwd": os.getcwd(),
    "files": files,
    "method": method,
    "method_source": method_source,
    "cli_method": cli_method,
    "env_method": env_method,
    "raw_cli_method": raw_cli_method,
    "raw_env_method": raw_env_method,
    "allow_method_override": bool(os.environ.get("SASE_COMMIT_METHOD_ALLOW_OVERRIDE")),
    "resume": resume,
    "pid": os.getppid(),
    "wrapper": "sase_git_commit",
}

target = Path(artifacts_dir) / "commit_skill_invoked.json"
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(marker, sort_keys=True) + "\n", encoding="utf-8")
PY
}

# --- Exit handler --------------------------------------------------------- #

function on_exit() {
  local exit_code=$?
  local now
  now=$(date +%s)
  local elapsed=$((now - SCRIPT_START_EPOCH))
  jlog "script_exit" "exit_code=${exit_code}" "duration_s=${elapsed}"
  exit "${exit_code}"
}
trap on_exit EXIT

# --- Main ----------------------------------------------------------------- #

branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")

jlog "script_start" \
  "args=$*" \
  "working_dir=$(pwd)" \
  "branch=${branch}" \
  "pid=$$"

write_invocation_marker "$@"

# Delegate to sase commit, forwarding all arguments.
set +e
sase commit "$@"
rc=$?
set -e

if [[ ${rc} -eq 0 ]]; then
  commit_hash=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
  jlog "commit" "result=ok" "commit_hash=${commit_hash}"
else
  jlog "commit" "result=failed" "exit_code=${rc}"
fi

exit "${rc}"
