from __future__ import annotations

import json

from click.testing import CliRunner

from autodebug.cli import _create_api_session, _read_jsonl_events, cli


def test_create_api_session_retries_idempotent_only_by_default(monkeypatch):
    monkeypatch.delenv("HIKAFLOW_RETRY_NON_IDEMPOTENT", raising=False)
    session = _create_api_session()
    adapter = session.adapters["https://"]
    allowed = {m.upper() for m in adapter.max_retries.allowed_methods}
    assert "GET" in allowed
    assert "POST" not in allowed


def test_create_api_session_allows_non_idempotent_when_opted_in(monkeypatch):
    monkeypatch.setenv("HIKAFLOW_RETRY_NON_IDEMPOTENT", "true")
    session = _create_api_session()
    adapter = session.adapters["https://"]
    allowed = {m.upper() for m in adapter.max_retries.allowed_methods}
    assert "POST" in allowed
    assert "PUT" in allowed


def test_read_jsonl_events_skips_malformed_lines(tmp_path, capsys):
    run_dir = tmp_path / "run"
    run_dir.mkdir()
    events = run_dir / "events.jsonl"
    events.write_text(
        json.dumps({"type": "A"}) + "\n" + "{not-json}\n" + json.dumps({"type": "B"}) + "\n",
        encoding="utf-8",
    )

    parsed = list(_read_jsonl_events(run_dir))
    assert [p["type"] for p in parsed] == ["A", "B"]
    err = capsys.readouterr().err
    assert "malformed event line" in err


def test_login_dev_requires_explicit_dev_token(monkeypatch):
    runner = CliRunner()
    monkeypatch.delenv("HIKAFLOW_DEV_TOKEN", raising=False)

    result = runner.invoke(cli, ["login", "--dev"])
    assert result.exit_code != 0
    assert "--dev requires HIKAFLOW_DEV_TOKEN" in result.output
