import pytest
import os
import json
from GramAddict.core.utils import is_ad, learn_ad_marker, get_learned_ad_markers

@pytest.fixture(autouse=True)
def clean_ad_markers():
    # Clean up any existing learned markers file before and after tests
    file_path = os.path.join(os.getcwd(), "learned_ad_markers.json")
    if os.path.exists(file_path):
        os.remove(file_path)
    import GramAddict.core.utils
    GramAddict.core.utils._LEARNED_AD_MARKERS_CACHE = None
    yield
    if os.path.exists(file_path):
        os.remove(file_path)
    GramAddict.core.utils._LEARNED_AD_MARKERS_CACHE = None

def test_learn_ad_marker_validates_against_xml():
    xml_dump = """<?xml version="1.0" encoding="utf-8"?>
    <hierarchy>
        <node class="android.widget.TextView" text="Sponsorisé" resource-id="com.instagram.android:id/some_id" content-desc=""/>
    </hierarchy>
    """
    
    # Attempt to learn a hallucinated marker
    learn_ad_marker("Hallucination", xml_dump)
    assert "hallucination" not in get_learned_ad_markers()
    
    # Attempt to learn an actual marker present in XML
    learn_ad_marker("Sponsorisé", xml_dump)
    assert "sponsorisé" in get_learned_ad_markers()

def test_is_ad_uses_learned_markers():
    xml_dump = """<?xml version="1.0" encoding="utf-8"?>
    <hierarchy>
        <node class="android.widget.TextView" text="Sponsorisé" resource-id="com.instagram.android:id/some_id" content-desc=""/>
        <node resource-id="row_feed_photo_profile_name" text="someone" />
    </hierarchy>
    """
    
    # Initially, it shouldn't recognize "Sponsorisé" because it's not in the hardcoded list
    assert is_ad(xml_dump) is False
    
    # Learn the new marker
    learn_ad_marker("Sponsorisé", xml_dump)
    
    # Now, is_ad should return True immediately without VLM
    assert is_ad(xml_dump) is True
