"""Run a small new study with the installed SquidSolver Pro CLI.

Requires Python 3.9+. Prepare your purchased solver in Pro, then quit the app.
This example demonstrates the workflow; its iteration count is not a claim
about convergence. Every run uses a new solve ID and output directory.
"""
import argparse
import json
import subprocess
import sys
import uuid
from pathlib import Path


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--solver", choices=("nlh", "plo4"), default="nlh")
    parser.add_argument("--exe", type=Path, help="Full path to the installed Pro executable")
    parser.add_argument("--iterations", type=int, default=100_000)
    args = parser.parse_args()
    if args.iterations <= 0:
        parser.error("--iterations must be positive")
    if args.exe:
        exe = args.exe.expanduser()
    elif sys.platform == "win32":
        exe = Path(r"C:\Program Files\SquidSolver Pro\squidsolver-pro-desktop.exe")
    elif sys.platform == "darwin":
        suffix = "Applications/SquidSolver Pro.app/Contents/MacOS/squidsolver-pro-desktop"
        exe = Path("/") / suffix
        if not exe.is_file():
            exe = Path.home() / suffix
    else:
        parser.error("Use Windows or macOS with SquidSolver Pro installed")
    if not exe.is_file():
        parser.error("Executable not found. Use --exe with your installation path")

    solve_id = f"river_{args.solver}_{uuid.uuid4().hex[:12]}"
    output = Path.cwd() / solve_id
    output.mkdir()
    command = [str(exe), "cli", "--solver", args.solver]

    def run(*argv):
        # communicate() drains both pipes. Check status before parsing stdout.
        result = subprocess.run(command + list(argv), capture_output=True,
                                text=True, encoding="utf-8")
        if result.stderr:
            print(result.stderr, file=sys.stderr, end="")
        if result.returncode:
            raise RuntimeError(f"Command failed with exit {result.returncode}: {' '.join(argv)}")
        return json.loads(result.stdout)

    example = "plo4-river" if args.solver == "plo4" else "nlh-river"
    config = run("config", "example", example)
    config_path = output / "spot.json"
    config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
    estimate = run("solve", "estimate", "--config", str(config_path))
    print("Memory estimate:", json.dumps(estimate, indent=2))
    run("solve", "create", "--config", str(config_path), "--id", solve_id,
        "--name", f"River study ({args.solver})")
    run("solve", "run", solve_id, "--iterations", str(args.iterations))
    for name, argv in (("solve", ("solve", "show", solve_id)),
                       ("root", ("node", "show", solve_id))):
        data = run(*argv)
        (output / f"{name}.json").write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
    board = "".join(config["scenario"]["board"])
    run("export", solve_id, "--streets", "postflop", "--board", board,
        "--out", str(output / "study.json.gz"))
    print(f"Saved solve: {solve_id}\nFiles: {output}\nCheck solve.json for progress and root.json for readout availability.")


if __name__ == "__main__":
    try:
        main()
    except (RuntimeError, OSError, json.JSONDecodeError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
