import pytest

from ankipan import HtmlWrappers, OngoingTask, OngoingTasks


@pytest.mark.parametrize("use_server_gpt", [True])
def test_flashcard_fields_example_sentences(
    generate_test_environment,
    data_dir,
    use_server_gpt,
    client_call_recorder,
):
    exposed_field_names = ["example_sentences"]

    testenv = generate_test_environment(
        field_names=exposed_field_names,
        example_sentence_sources=[
            "ankipan_private/series/how to sell drugs online",
            "ankipan_private/series/Friends",
            "ankipan_default/youtube/video_collections/akrobatik",
        ],
        extract_kwargs={"lemma_counts": {"genau": 1}},
        collection_kwargs = {'use_server_gpt': use_server_gpt},
        learning_lang="de",
    )

    testenv.collection.trigger_fields(testenv.deck_name)
    for exposed_field_name in exposed_field_names:
        assert isinstance(testenv.get_flashcard_field(exposed_field_name), OngoingTasks)

    testenv.reload()
    for exposed_field_name in exposed_field_names:
        assert isinstance(testenv.get_flashcard_field(exposed_field_name), OngoingTasks)

    testenv.collect_until_ready(field_names=exposed_field_names)
    for exposed_field_name in exposed_field_names:
        assert isinstance(testenv.get_flashcard_field(exposed_field_name), HtmlWrappers.CardSection)
    testenv.collection.save()

    with open(data_dir / '.field.html', 'w', encoding='utf-8') as f:
        f.write(testenv.first_card.standalone_backside())


def test_flashcard_fields_example_sentences_multi_server_quota_and_collect(
    generate_test_environment,
    data_dir,
    client_call_recorder,
):
    exposed_field_names = ["example_sentences"]

    testenv = generate_test_environment(
        field_names=exposed_field_names,
        example_sentence_sources={
            'ankipan_private/series/love is blind':0.2,
            'ankipan_private/series/how to sell drugs online':0.5,
            'ankipan_default/youtube/video_collections/akrobatik':1,
        },
        extract_kwargs={"lemma_counts": {"klappen": 1}},
        collection_kwargs={"use_server_gpt": True},
        learning_lang="de",
    )
    testenv.collection.set_n_example_sentences(10)

    testenv.collection.trigger_fields(testenv.deck_name)
    field_val = testenv.get_flashcard_field("example_sentences")
    assert isinstance(field_val, OngoingTasks)
    assert len(field_val.tasks) == 2
    testenv.collect_until_ready(field_names=exposed_field_names, poll_interval=0)
    assert isinstance(testenv.get_flashcard_field("example_sentences"), HtmlWrappers.CardSection)

    with open(data_dir / ".field_multi_server.html", "w", encoding="utf-8") as f:
        f.write(testenv.first_card.standalone_backside())
