import pytest
import os
from backend.SearchEpc import SearchEpc  # Replace with your actual module name
from dotenv import load_dotenv

# If this backend/.env file is present, we load it
if os.path.exists("backend/.env"):
    load_dotenv("backend/.env")


class TestSearchEpcIntegration:

    @pytest.fixture
    def epc_auth_token(self):
        return os.getenv("EPC_AUTH_TOKEN")

    @pytest.mark.parametrize(
        "address, postcode, uprn, skip_os, lmk_key, n_old_epcs",
        [
            # Test case 1: Valid address and postcode, skipping OS
            # In this case, the property is an individual flat but the uprn associated to the
            # EPC is for the building as a whole, possibly because there was a conversion of sorts
            ("Garden Flat, 48 Bedminster Parade", "BS3 4HS", 308249, True,
             "260907a5431fa073d193cc6bbec51fbf1ba9a61845ab2503f85aa19ce3ed6afd", 1),

            # Test case 2: Another valid address and postcode
            # In this case, the newest EPC, does not have a uprn associated to it. If we did a search by
            # uprn, we would get an old EPC
            ("Flat 8, Hainton House", "DN32 9AQ", "", True,
             "bd1149a20a73397184f07a9955f872424826e70f4870c058d71be887766ee1f8", 2),
            # Test case 3: When we make a request to the API for this property, we get back results for
            # flats 1, 2 and 3. We have some logic to handle the response so that we get back flat 1
            ("Flat 1, 1 Tottenham Street, London", "W1T 2AE", 5167411, True,
             "3e6414d7f15f4cf7a69dc20c469bcf043d31a49239b183f1bd0c0e1aafa23c93", 0),

        ],
    )
    def test_find_property(self, epc_auth_token, address, postcode, uprn, skip_os, lmk_key, n_old_epcs):
        """
        Integration test for `find_property`, making actual API calls.
        """
        # Provide your actual API keys or tokens here
        os_api_key = ""

        # Initialize the SearchEpc instance
        epc_searcher = SearchEpc(
            address1=address,
            postcode=postcode,
            uprn=uprn,
            auth_token=epc_auth_token,
            os_api_key=os_api_key,
        )

        # Execute the method
        epc_searcher.find_property(skip_os=skip_os)

        # We check that we have the correct epc
        assert epc_searcher.newest_epc["lmk-key"] == lmk_key
        assert len(epc_searcher.older_epcs) == n_old_epcs

    def test_search_housenumber(self):
        eg1 = 'Flat A11, Mortimer House, Grendon Road, Exeter'
        res1 = SearchEpc.get_house_number(eg1, None)
        assert res1 == "A11"

        eg2 = 'Flat A9, Mortimer House, Grendon Road, Exeter, EX1 2NL'
        res2 = SearchEpc.get_house_number(eg2, None)
        assert res2 == "A9"
