#!/usr/bin/env python3
"""puzzle_cli.py — thin CLI bridge so the Node.js Telegram bot can call the
pure-python crypto_puzzle solver. No secrets; prints JSON to stdout only.

Usage:
    python3 tools/puzzle_cli.py solve "<puzzle text>"
    python3 tools/puzzle_cli.py classify "<puzzle text>"

The Telegram bot shells out to this with python3's absolute path and parses the
JSON answer. Nothing is written to disk; only stdout is parsed.
"""

from __future__ import annotations

import os
import subprocess
import sys

_HERE = os.path.dirname(os.path.abspath(__file__))
_PUZZLE = os.path.join(_HERE, "crypto_puzzle.py")


def _python() -> str:
    # prefer the system python that has coincurve-style deps; fall back to env python3
    candidates = [
        "/usr/bin/python3",
        "/usr/local/bin/python3",
        "/data/data/com.termux/files/usr/bin/python3",
        sys.executable,
    ]
    for c in candidates:
        if c and os.path.exists(c):
            return c
    return sys.executable


def solve(text: str) -> dict:
    cmd = [_python(), _PUZZLE, "solve", text]
    proc = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
    if proc.returncode != 0:
        return {"error": f"solve rc={proc.returncode} stderr={proc.stderr[:200]}"}
    try:
        return __import__("json").loads(proc.stdout)
    except Exception as e:
        return {"error": f"bad json: {e} stdout={proc.stdout[:200]}", "raw": proc.stdout}


def classify(text: str) -> str:
    cmd = [_python(), _PUZZLE, "classify", text]
    proc = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
    if proc.returncode != 0:
        return ""
    return proc.stdout.strip()


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("usage: puzzle_cli.py <solve|classify> <text>", file=sys.stderr)
        sys.exit(2)
    if sys.argv[1] == "solve":
        print(__import__("json").dumps(solve(sys.argv[2]), ensure_ascii=False))
    elif sys.argv[1] == "classify":
        print(classify(sys.argv[2]))
    else:
        print("unknown cmd", file=sys.stderr)
