from __future__ import annotations

import json

from nbdraw.cli import main, main_legacy


def test_draw_dry_run_outputs_payload(monkeypatch, capsys, tmp_path):
    config = tmp_path / "cfg.json"
    config.write_text('{"client": {"api_key": "k"}}', encoding="utf-8")
    monkeypatch.setenv("GRSAI_API_KEY", "env-key")
    code = main(["draw", "--config", str(config), "--prompt", "hello", "--dry-run"])
    assert code == 0

    payload = json.loads(capsys.readouterr().out)
    assert payload["prompt"] == "hello"
    assert payload["model"] == "nano-banana-fast"


def test_legacy_entry_still_works(monkeypatch, capsys):
    monkeypatch.setenv("GRSAI_API_KEY", "env-key")
    code = main_legacy(["--prompt", "legacy", "--dry-run"], show_warning=False)
    assert code == 0

    payload = json.loads(capsys.readouterr().out)
    assert payload["prompt"] == "legacy"


def test_json_output_contract(monkeypatch, capsys, tmp_path):
    config = tmp_path / "cfg.json"
    config.write_text('{\"client\": {\"api_key\": \"k\"}}', encoding="utf-8")

    class FakeClient:
        def __init__(self, *args, **kwargs):
            del args, kwargs

        def draw_and_wait(self, **kwargs):
            del kwargs
            return "task-1", "https://example.com/a.png", {"status": "succeeded", "foo": "bar"}

    monkeypatch.setattr("nbdraw.cli.GrsAIClient", FakeClient)
    monkeypatch.setattr(
        "nbdraw.cli.download_image",
        lambda *args, **kwargs: "/tmp/outputs/task-1.png",
    )

    code = main(
        [
            "draw",
            "--config",
            str(config),
            "--prompt",
            "json contract",
            "--json",
            "--quiet",
        ]
    )
    assert code == 0

    data = json.loads(capsys.readouterr().out)
    for key in ("task_id", "url", "local_path", "status", "model", "elapsed_seconds", "raw"):
        assert key in data
    assert data["task_id"] == "task-1"
    assert data["status"] == "succeeded"
