#!/usr/bin/env bash
# techviz CLI 래퍼. 도구는 별도 저장소에 있고 이 저장소에는 스킬만 들어와 있다.
# 경로가 다르면 TECHVIZ_HOME 으로 알려 준다.
set -euo pipefail
TECHVIZ_HOME="${TECHVIZ_HOME:-/home/donghyeon/workspace/ai-tool/technical-visualization-haness}"
if [ ! -d "$TECHVIZ_HOME/src/techviz" ]; then
  echo "techviz 도구를 찾지 못했다: $TECHVIZ_HOME" >&2
  echo "TECHVIZ_HOME 으로 technical-visualization-haness 경로를 알려 준다." >&2
  exit 1
fi
export TECHVIZ_HOME

if [ "${1:-}" = "render" ]; then
  PYTHONPATH="$TECHVIZ_HOME/src${PYTHONPATH:+:$PYTHONPATH}" python3 -m techviz "$@"

  spec="${2:-}"
  out=""
  args=("$@")
  for ((i = 0; i < ${#args[@]}; i++)); do
    case "${args[$i]}" in
      -o|--output|--out-dir)
        if (( i + 1 < ${#args[@]} )); then
          out="${args[$((i + 1))]}"
        fi
        ;;
    esac
  done

  if [ -n "$spec" ] && [ -n "$out" ]; then
    python3 - "$spec" "$out" <<'PY'
from __future__ import annotations

import hashlib
import json
import pathlib
import sys

spec_path = pathlib.Path(sys.argv[1])
out_dir = pathlib.Path(sys.argv[2])
if not spec_path.is_file() or not out_dir.is_dir():
    raise SystemExit(0)

spec = json.loads(spec_path.read_text(encoding="utf-8"))
spec_id = spec.get("id")
if not isinstance(spec_id, str) or not spec_id:
    raise SystemExit(0)

manifest_path = out_dir / f"{spec_id}.manifest.json"
if not manifest_path.is_file():
    raise SystemExit(0)

manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
hashes: dict[str, str] = {}
for name in manifest.get("outputs") or []:
    if not isinstance(name, str):
        continue
    path = out_dir / name
    if not path.is_file():
        continue
    hashes[name] = hashlib.sha256(path.read_bytes()).hexdigest()

manifest["source_spec_file_sha256"] = hashlib.sha256(spec_path.read_bytes()).hexdigest()
manifest["output_sha256"] = hashes
manifest_path.write_text(
    json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
    encoding="utf-8",
)
PY
  fi
  exit 0
fi

PYTHONPATH="$TECHVIZ_HOME/src${PYTHONPATH:+:$PYTHONPATH}" exec python3 -m techviz "$@"
