# retoor <retoor@molodetz.nl>

import json

from devplacepy.services.bot.handles import MAX_HANDLE_LEN
from devplacepy.services.bot.llm import LLMClient


def _client(reply: str) -> LLMClient:
    client = LLMClient(
        api_key="test",
        api_url="http://example.invalid",
        model="molodetz",
        input_cost_per_1m=0.0,
        output_cost_per_1m=0.0,
    )
    client._raw_call = lambda system, prompt, temperature=1.0: reply
    return client


def test_generate_handle_candidates_parses_and_sanitizes():
    reply = json.dumps({"handles": ["null_byte", "john.smith", "seg fault!!", "c0d3r"]})
    handles = _client(reply).generate_handle_candidates("grumpy_senior")
    assert handles == ["null_byte", "johnsmith", "segfault", "c0d3r"]


def test_generate_handle_candidates_dedupes_case_insensitively():
    reply = json.dumps({"handles": ["NullByte", "nullbyte", "Daemon", "daemon"]})
    handles = _client(reply).generate_handle_candidates("minimalist")
    assert [handle.lower() for handle in handles] == ["nullbyte", "daemon"]


def test_generate_handle_candidates_drops_empty_results():
    reply = json.dumps({"handles": ["", "...", "!!!", "kernelpanic"]})
    handles = _client(reply).generate_handle_candidates("rebel")
    assert handles == ["kernelpanic"]


def test_generate_handle_candidates_caps_length():
    reply = json.dumps({"handles": ["x" * 40]})
    handles = _client(reply).generate_handle_candidates("mentor")
    assert len(handles[0]) == MAX_HANDLE_LEN


def test_generate_handle_candidates_handles_bad_json():
    assert _client("not json at all").generate_handle_candidates("academic_type") == []


def test_generate_handle_candidates_handles_missing_key():
    assert _client(json.dumps({"other": []})).generate_handle_candidates("mentor") == []
