from __future__ import annotations

import argparse
from types import SimpleNamespace

import pytest

import cirtusai.cli as cli


class DummyIdentity:
    name = "Agent"
    id = "id"
    type = "personal"
    status = "active"
    create_time = "2024-01-01"
    reputation = None
    rate_limit = None
    assets = []
    linked_platforms = []


def test_cmd_init_success(monkeypatch, capsys):
    monkeypatch.setattr(cli.CirtusClient, "register", lambda *args, **kwargs: {})
    monkeypatch.setattr(cli.CirtusClient, "login", lambda *args, **kwargs: {"access_token": "tok"})

    def fake_create_api_key(self, *args, **kwargs):
        return {"secret": "key"}

    monkeypatch.setattr(cli.CirtusClient, "create_api_key", fake_create_api_key)

    saved = {}

    def fake_save(api_key, base_url, agent_name):
        saved["api_key"] = api_key
        saved["base_url"] = base_url
        saved["agent_name"] = agent_name

    monkeypatch.setattr(cli, "save_credentials", fake_save)

    args = SimpleNamespace(url="https://api", agent_name="agent", password="pass")
    cli.cmd_init(args)
    assert saved["api_key"] == "key"
    out = capsys.readouterr().out
    assert "Successfully registered" in out or "logging in instead" in out


def test_cmd_identity(monkeypatch, capsys):
    monkeypatch.setattr(cli, "get_client", lambda: SimpleNamespace(get_identity=lambda: DummyIdentity()))
    cli.cmd_identity(argparse.Namespace())
    out = capsys.readouterr().out
    assert "Identity: Agent" in out


def test_cmd_mail_send_requires_args(capsys):
    args = argparse.Namespace(to=None, subject=None, body=None)
    with pytest.raises(SystemExit):
        cli.cmd_mail_send(args)
    err = capsys.readouterr().err
    assert "--to" in err


def test_cmd_mail_list_empty(monkeypatch, capsys):
    client = SimpleNamespace(list_messages=lambda **_: [])
    monkeypatch.setattr(cli, "get_client", lambda: client)
    args = argparse.Namespace(folder="inbox", limit=10, unread=None)
    cli.cmd_mail_list(args)
    out = capsys.readouterr().out
    assert "No messages found" in out


def test_cmd_stake_create_missing_tier(capsys):
    args = argparse.Namespace(tier=None, lock_days=None)
    with pytest.raises(SystemExit):
        cli.cmd_stake_create(args)
    err = capsys.readouterr().err
    assert "--tier is required" in err


def test_cmd_stake_list_empty(monkeypatch, capsys):
    client = SimpleNamespace(list_stakes=lambda: {"items": []})
    monkeypatch.setattr(cli, "get_client", lambda: client)
    cli.cmd_stake_list(argparse.Namespace())
    out = capsys.readouterr().out
    assert "No stakes found" in out


def test_cmd_logout_clears_credentials(monkeypatch, capsys):
    called = {}
    monkeypatch.setattr(cli, "clear_credentials", lambda: called.setdefault("ok", True))
    cli.cmd_logout(argparse.Namespace())
    assert called.get("ok") is True
    assert "Logged out successfully" in capsys.readouterr().out
