#!/usr/bin/env python3
"""gemini_commands_to_skills.py - convert Gemini CLI custom commands (.toml) into
Antigravity CLI skills (<name>/SKILL.md). MIT License, AgentKit Co (agentkitco.com).

Dry run by default. Nothing is overwritten. Needs Python 3.11+ (tomllib).

  python3 gemini_commands_to_skills.py                 # preview .gemini/commands -> .agents/skills
  python3 gemini_commands_to_skills.py --write         # write the files
  python3 gemini_commands_to_skills.py --src ~/.gemini/commands --dest ~/.gemini/config/skills --write

Gemini file .gemini/commands/git/commit.toml (/git:commit) becomes skill
"git-commit" (/git-commit). Placeholders are handled like this:
  {{args}}  -> replaced with a plain-English note (skills get your request as text)
  !{...}    -> kept, but flagged: shell injection is a Gemini CLI command feature
  @{...}    -> kept, but flagged: file injection is a Gemini CLI command feature
Review every flagged skill before you rely on it.
"""
import argparse, os, re, sys
try:
    import tomllib
except ImportError:
    sys.exit("Python 3.11+ is required (tomllib).")

ARGS_NOTE = "the user's request that came with this command"

def skill_name(rel):
    stem = os.path.splitext(rel)[0].replace(os.sep, "/")
    name = re.sub(r"[^a-z0-9]+", "-", stem.lower()).strip("-")
    return name or "command"

def yaml_str(s):
    s = " ".join(str(s).split())
    return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'

def convert(path, rel):
    with open(path, "rb") as f:
        data = tomllib.load(f)
    prompt = data.get("prompt")
    if not isinstance(prompt, str) or not prompt.strip():
        raise ValueError("missing required 'prompt' string")
    name = skill_name(rel)
    gem = "/" + os.path.splitext(rel)[0].replace(os.sep, ":")
    desc = data.get("description") or f"Runs the former Gemini CLI command {gem}. Use when the user asks for {name.replace('-', ' ')}."
    flags = []
    body = prompt
    if "{{args}}" in body:
        body = body.replace("{{args}}", f"<{ARGS_NOTE}>")
        flags.append("{{args}} replaced with a note")
    if "!{" in body:
        flags.append("contains !{...} shell injection: rewrite as an instruction to run the command")
    if "@{" in body:
        flags.append("contains @{...} file injection: rewrite as an instruction to read the file")
    md = ["---", f"name: {name}", f"description: {yaml_str(desc)}", "---", "",
          f"<!-- Converted from Gemini CLI command {gem} ({rel}) by gemini_commands_to_skills.py. -->", ""]
    if "{{args}}" in prompt:
        md += [f"Treat <{ARGS_NOTE}> below as whatever the user typed after /{name}. If they typed nothing, ask what they want.", ""]
    md.append(body.rstrip() + "\n")
    return name, "\n".join(md), flags

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--src", default=".gemini/commands")
    ap.add_argument("--dest", default=".agents/skills")
    ap.add_argument("--write", action="store_true", help="write files (default is a dry run)")
    a = ap.parse_args()
    src, dest = os.path.expanduser(a.src), os.path.expanduser(a.dest)
    if not os.path.isdir(src):
        sys.exit(f"No commands folder at {src}")
    done = skipped = errors = 0
    seen = {}
    for d, _, files in os.walk(src):
        for fn in sorted(files):
            if not fn.endswith(".toml"):
                continue
            path = os.path.join(d, fn); rel = os.path.relpath(path, src)
            try:
                name, text, flags = convert(path, rel)
            except Exception as e:
                print(f"ERROR {rel}: {e}"); errors += 1; continue
            if name in seen:
                print(f"SKIP  {rel}: name '{name}' already used by {seen[name]}"); skipped += 1; continue
            seen[name] = rel
            out = os.path.join(dest, name, "SKILL.md")
            if os.path.exists(out):
                print(f"SKIP  {rel}: {out} exists (not overwritten)"); skipped += 1; continue
            tag = "WRITE" if a.write else "PLAN "
            print(f"{tag} {rel} -> {out}" + "".join(f"\n      ! {x}" for x in flags))
            if a.write:
                os.makedirs(os.path.dirname(out), exist_ok=True)
                with open(out, "w") as f:
                    f.write(text)
            done += 1
    print(f"\n{done} converted{'' if a.write else ' (dry run, add --write)'}, {skipped} skipped, {errors} errors")
    if a.write and done:
        print("In Antigravity CLI run /skills reload (or start a new conversation) to see the new slash commands.")
    return 1 if errors else 0

if __name__ == "__main__":
    sys.exit(main())
