"""
Fixture-driven end-to-end test for HyundaiCardScraper.
Starts from local login HTML (file://) and asserts structured data is returned.
"""

import os
from pathlib import Path

import pytest

from libeunhaeng.hyundai_card_scraper import HyundaiCardScraper


@pytest.fixture
def base_fixture_url():
    fixtures_root = Path(__file__).parent / "fixtures" / "hyundai_card"
    return f"file://{fixtures_root / '01_main_page.html'}"


@pytest.mark.asyncio
async def test_navigate_to_login(base_fixture_url):
    """Test navigation to login page."""
    async with HyundaiCardScraper(headless=True, base_url=base_fixture_url) as scraper:
        await scraper.navigate_to_login()
        assert scraper.page.url.startswith("file://")


@pytest.mark.asyncio
async def test_open_id_login_form(base_fixture_url):
    """Test opening ID login form."""
    async with HyundaiCardScraper(headless=True, base_url=base_fixture_url) as scraper:
        await scraper.navigate_to_login()
        await scraper.open_id_login_form()

        id_form_active = await scraper.page.evaluate(
            'document.getElementById("idLoginForm").classList.contains("active")'
        )
        assert id_form_active is True


@pytest.mark.asyncio
async def test_enter_user_id(base_fixture_url):
    """Test entering user ID."""
    async with HyundaiCardScraper(headless=True, base_url=base_fixture_url) as scraper:
        await scraper.navigate_to_login()
        await scraper.open_id_login_form()
        await scraper.enter_user_id("test_user_123")

        filled_value = await scraper.page.evaluate('document.getElementById("webMbrId").value')
        assert filled_value == "test_user_123"


@pytest.mark.asyncio
async def test_get_transactions(monkeypatch):
    """Test transaction extraction."""
    fixtures_root = Path(__file__).parent / "fixtures" / "hyundai_card"
    transactions_url = f"file://{fixtures_root / '03_transactions.html'}"

    # Set the transactions URL environment variable
    monkeypatch.setenv("HYUNDAI_CARD_TRANSACTIONS_URL", transactions_url)

    async with HyundaiCardScraper(headless=True, base_url=transactions_url) as scraper:
        # Call the scraper's get_transactions method
        transactions = await scraper.get_transactions()

        # Verify the data
        assert len(transactions) > 0
        assert transactions[0]["merchant"] == "스타벅스강남점"
        assert transactions[0]["amount"] == "6,500원"
        assert transactions[0]["card_name"] == "the Purple Edition"


@pytest.mark.asyncio
async def test_main_integration(monkeypatch, base_fixture_url):
    """Test main workflow integration."""
    fixtures_root = Path(__file__).parent / "fixtures" / "hyundai_card"
    transactions_fixture_url = f"file://{fixtures_root / '03_transactions.html'}"

    # Setup environment variables
    monkeypatch.setenv("HYUNDAI_CARD_BASE_URL", base_fixture_url)
    monkeypatch.setenv("HYUNDAI_CARD_TRANSACTIONS_URL", transactions_fixture_url)
    monkeypatch.setenv("HYUNDAI_CARD_HEADLESS", "true")
    monkeypatch.setenv("HYUNDAI_CARD_USER_ID", "test_user_123")
    monkeypatch.setenv("HYUNDAI_CARD_PASSWORD", "abc123")
    monkeypatch.setenv("HYUNDAI_CARD_CREDIT_CARD_PIN", "1234")

    # Emulate main() logic
    user_id = os.getenv("HYUNDAI_CARD_USER_ID")
    password = os.getenv("HYUNDAI_CARD_PASSWORD")
    pin = os.getenv("HYUNDAI_CARD_CREDIT_CARD_PIN")
    headless_env = os.getenv("HYUNDAI_CARD_HEADLESS", "false").lower() == "true"
    base_url = os.getenv("HYUNDAI_CARD_BASE_URL")

    result = []
    async with HyundaiCardScraper(headless=headless_env, base_url=base_url) as scraper:
        # Login
        await scraper.login(user_id, password, pin)

        # Get transactions
        result = await scraper.get_transactions()

    # Verify the result structure
    assert result is not None
    assert isinstance(result, list)
    assert len(result) > 0

    # Verify transaction structure
    first_txn = result[0]
    assert "merchant" in first_txn
    assert "amount" in first_txn
    assert "card_name" in first_txn
    assert "transacted_at" in first_txn
    assert "installment" in first_txn

    # Verify actual data from fixture
    assert first_txn["merchant"] == "스타벅스강남점"
    assert first_txn["amount"] == "6,500원"
