#!/usr/bin/env bash
set -euo pipefail

task_file="${1:-}"
if [[ -z "$task_file" || ! -f "$task_file" ]]; then
  echo "[orchestrator-worker] missing task file argument" >&2
  exit 1
fi

worker_exec="${MOSAIC_WORKER_EXEC:-}"
if [[ -z "$worker_exec" ]]; then
  if command -v codex >/dev/null 2>&1; then
    worker_exec="codex -p"
  elif command -v opencode >/dev/null 2>&1; then
    worker_exec="opencode -p"
  else
    echo "[orchestrator-worker] set MOSAIC_WORKER_EXEC to your worker command (example: 'codex -p' or 'opencode -p')" >&2
    exit 1
  fi
fi

prompt="$(python3 - "$task_file" <<'PY'
import json
import sys
from pathlib import Path

task = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
task_id = str(task.get("id", "TASK"))
title = str(task.get("title", ""))
description = str(task.get("description", ""))
meta = task.get("metadata", {}) or {}
issue = str(meta.get("issue", ""))
repo = str(meta.get("repo", ""))
branch = str(meta.get("branch", ""))
depends = task.get("depends_on", [])
if isinstance(depends, list):
    depends_str = ", ".join(str(x) for x in depends)
else:
    depends_str = str(depends)

print(
    f"""Read ~/.config/mosaic/STANDARDS.md, then AGENTS.md and SOUL.md (if present).
Complete this queued task fully.

Task ID: {task_id}
Title: {title}
Description: {description}
Issue: {issue}
Repo hint: {repo}
Branch hint: {branch}
Depends on: {depends_str}

Requirements:
- Implement and verify the task end-to-end.
- Keep changes scoped to this task.
- Run project checks and tests relevant to touched code.
- Return with a concise summary of what changed and verification results.
"""
)
PY
)"

PROMPT="$prompt" bash -lc "$worker_exec \"\$PROMPT\""
