#!/bin/bash
# Sync the vendored AutoX SQL tuning skill into agentkit/skills.
#
# Usage:
#   ./scripts/sync-autox-skill.sh
#   AUTOX_REF=<branch-or-tag-or-sha> ./scripts/sync-autox-skill.sh

set -euo pipefail

UPSTREAM_REPO="${AUTOX_REPO:-https://github.com/AilinKid/AutoX.git}"
UPSTREAM_REF="${AUTOX_REF:-main}"
TARGET_DIR="${AUTOX_TARGET_DIR:-agentkit/skills/tidb-query-tuning-autox}"
TEMP_DIR="$(mktemp -d)"

cleanup() {
  rm -rf "$TEMP_DIR"
}
trap cleanup EXIT

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"

echo "Syncing AutoX SQL skill from ${UPSTREAM_REPO}@${UPSTREAM_REF}..."

git clone --no-tags "$UPSTREAM_REPO" "$TEMP_DIR" >/dev/null
git -C "$TEMP_DIR" fetch origin "$UPSTREAM_REF" >/dev/null 2>&1 || true
git -C "$TEMP_DIR" checkout --detach "$UPSTREAM_REF" >/dev/null

UPSTREAM_COMMIT="$(git -C "$TEMP_DIR" rev-parse HEAD)"
SOURCE_DIR="$TEMP_DIR/skills/autox-optimize-sql"

if [ ! -f "$SOURCE_DIR/SKILL.md" ]; then
  echo "AutoX source skill not found: $SOURCE_DIR/SKILL.md" >&2
  exit 1
fi

rm -rf "$TARGET_DIR"
mkdir -p "$TARGET_DIR"
cp -a "$SOURCE_DIR/." "$TARGET_DIR/"

mkdir -p "$TARGET_DIR/references/upstream" "$TARGET_DIR/references/helpers"
cp "$TEMP_DIR/LICENSE" "$TARGET_DIR/LICENSE"
cp "$TEMP_DIR/README.md" "$TARGET_DIR/references/upstream/README.md"
cp "$TEMP_DIR/AGENTS.md" "$TARGET_DIR/references/upstream/AGENTS.md"
cp "$TEMP_DIR/docs/autox-sql-tuning-spec.md" "$TARGET_DIR/references/upstream/autox-sql-tuning-spec.md"
cp "$TEMP_DIR/skills/autox-compare-plans/SKILL.md" "$TARGET_DIR/references/helpers/autox-compare-plans.md"
cp "$TEMP_DIR/skills/autox-explore-sql/SKILL.md" "$TARGET_DIR/references/helpers/autox-explore-sql.md"

python3 - "$TARGET_DIR" "$UPSTREAM_REPO" "$UPSTREAM_REF" "$UPSTREAM_COMMIT" <<'PY'
from __future__ import annotations

import json
import sys
from datetime import datetime, timezone
from pathlib import Path

target = Path(sys.argv[1])
repo = sys.argv[2]
ref = sys.argv[3]
commit = sys.argv[4]

skill_path = target / "SKILL.md"
text = skill_path.read_text(encoding="utf-8")

if not text.startswith("---\n"):
    raise SystemExit("Expected AutoX SKILL.md to start with frontmatter")

_, frontmatter, body = text.split("---\n", 2)
frontmatter_lines = []
for line in frontmatter.splitlines():
    if line.startswith("name: "):
        frontmatter_lines.append("name: tidb-query-tuning-autox")
    elif line.startswith("description: "):
        frontmatter_lines.append(
            "description: Deep SQL plan and query-workload diagnosis for confirmed "
            "Investibook sql_plan_or_query cases, adapted from AutoX."
        )
    else:
        frontmatter_lines.append(line)

adapter = """# Investibook Adapter Boundary

This is a vendored AutoX SQL tuning skill adapted for Investibook diagnosis.
Load it only after the top-level diagnosis has identified `sql_plan_or_query`
as a primary or material contributing candidate and the SQL specialist causal
checks have passed.

When used by `diagnosis-analyst`:

- Consume existing Investibook evidence under `evidences/`, especially
  `evidence_summary_for_agent.json` or `.txt`, `queries.json`, decoded plans,
  TopSQL, SlowQuery, schema/statistics excerpts, and raw artifacts explicitly
  cited by the handoff.
- Do not run AutoX fleet discovery, AutoX evidence-collection scripts, Clinic
  collection commands, or production SQL. `diagnosis-analyst` is read-only and
  cannot use data-access skills.
- Treat upstream evidence-collection, batch, and local-validation workflows as
  future runner/data-access instructions. In the current Investibook adapter,
  they are references for evidence shape and validation vocabulary, not commands
  to execute.
- Preserve the production safety boundary: generated Binding, Index, TiFlash,
  or hint SQL is review-only and must not be executed.
- Output SQL-internal diagnosis as evidence-backed subtype candidates such as
  `scan_amplification`, `cardinality_error`, `wrong_access_path`,
  `wrong_join_plan`, `plan_instability`, `cop_seek_amplification`,
  `order_path_tradeoff`, or `non_optimizer_bottleneck`.

Use AutoX to adjudicate the SQL mechanism and optimizer-action direction; do
not use it to override the top-level causal classification or turn an
affected-only query into a root cause.

"""

skill_path.write_text(
    "---\n"
    + "\n".join(frontmatter_lines).rstrip()
    + "\n---\n\n"
    + adapter
    + body.lstrip(),
    encoding="utf-8",
)

agent_yaml = target / "agents" / "openai.yaml"
if agent_yaml.exists():
    agent_text = agent_yaml.read_text(encoding="utf-8")
    agent_text = agent_text.replace("AutoX Optimize SQL", "TiDB Query Tuning AutoX")
    agent_text = agent_text.replace("$autox-optimize-sql", "$tidb-query-tuning-autox")
    agent_text = agent_text.replace(
        'default_prompt: "Use $tidb-query-tuning-autox to diagnose read-only TiDB Cloud slow SELECT statements; for a generic cluster review, scan the global top 10 across all active Dedicated clusters over the last 24 hours."',
        'default_prompt: "Use $tidb-query-tuning-autox only after Investibook has confirmed sql_plan_or_query; consume existing evidence and produce SQL-internal subtype diagnosis and review-only recommendations."',
    )
    agent_yaml.write_text(agent_text, encoding="utf-8")

source = {
    "upstream_repo": repo,
    "upstream_ref": ref,
    "upstream_commit": commit,
    "synced_at": datetime.now(timezone.utc).isoformat(),
    "source_paths": [
        "skills/autox-optimize-sql",
        "skills/autox-compare-plans/SKILL.md",
        "skills/autox-explore-sql/SKILL.md",
        "docs/autox-sql-tuning-spec.md",
        "README.md",
        "AGENTS.md",
        "LICENSE",
    ],
    "local_adaptations": [
        "Skill name rewritten to tidb-query-tuning-autox.",
        "Investibook adapter boundary prepended to SKILL.md.",
        "Helper skills copied as references/helpers/*.md instead of active top-level skills.",
    ],
}
(target / "UPSTREAM.json").write_text(json.dumps(source, indent=2, sort_keys=True) + "\n", encoding="utf-8")
PY

python3 - "$TARGET_DIR" <<'PY'
from __future__ import annotations

import sys
from pathlib import Path

target = Path(sys.argv[1])
required = [
    "SKILL.md",
    "SUBSKILLS_INDEX.md",
    "references/case-contract.md",
    "workflow/diagnosis-classification/SUBSKILL.md",
    "workflow/final-report/SUBSKILL.md",
    "references/helpers/autox-compare-plans.md",
    "references/helpers/autox-explore-sql.md",
    "LICENSE",
    "UPSTREAM.json",
]
missing = [path for path in required if not (target / path).is_file()]
if missing:
    raise SystemExit("Missing synced AutoX files: " + ", ".join(missing))

nested_skills = [path for path in target.rglob("SKILL.md") if path != target / "SKILL.md"]
if nested_skills:
    raise SystemExit("Nested active SKILL.md files are not allowed: " + ", ".join(map(str, nested_skills)))

print(f"Validated synced AutoX skill at {target}")
PY

echo ""
echo "Successfully synced AutoX SQL skill to $TARGET_DIR"
echo "Upstream commit: $UPSTREAM_COMMIT"
