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

import os
from pathlib import Path

import pytest

from libeunhaeng.shinhan_card_scraper import ShinhanCardScraper


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


@pytest.mark.asyncio
async def test_open_id_login_form_shows_id_fields(base_fixture_url):
    async with ShinhanCardScraper(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_sets_input_value(base_fixture_url):
    async with ShinhanCardScraper(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("fixture_card_user")

        filled_value = await scraper.page.evaluate('document.getElementById("t01.memid").value')
        assert filled_value == "fixture_card_user"


@pytest.mark.asyncio
async def test_click_next_button_reveals_password_section(base_fixture_url):
    async with ShinhanCardScraper(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("fixture_card_user")
        await scraper.click_next_button()

        password_section_display = await scraper.page.evaluate(
            'document.getElementById("passwordSection").style.display'
        )
        assert password_section_display == "block"


@pytest.mark.asyncio
async def test_enter_password_via_keyboard_masks_input(base_fixture_url):
    async with ShinhanCardScraper(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("fixture_card_user")
        await scraper.click_next_button()
        await scraper.enter_password_via_keyboard("abc@123")

        masked_value = await scraper.page.evaluate('document.getElementById("pwd").value')
        assert masked_value == "*" * len("abc@123")


@pytest.mark.asyncio
async def test_login_redirects_to_home(base_fixture_url):
    async with ShinhanCardScraper(headless=True, base_url=base_fixture_url) as scraper:
        await scraper.login("fixture_card_user", "abc@123")

        assert "home_page.html" in scraper.page.url


@pytest.mark.asyncio
async def test_card_main_returns_transactions(monkeypatch, base_fixture_url):
    monkeypatch.setenv("SHINHAN_CARD_BASE_URL", base_fixture_url)
    monkeypatch.setenv("SHINHAN_CARD_HEADLESS", "true")
    monkeypatch.setenv("SHINHAN_CARD_USER_ID", "fixture_card_user")
    monkeypatch.setenv("SHINHAN_CARD_PASSWORD", "abc@123")

    # Emulate main() logic
    user_id = os.getenv("SHINHAN_CARD_USER_ID")
    password = os.getenv("SHINHAN_CARD_PASSWORD")
    headless_env = os.getenv("SHINHAN_CARD_HEADLESS", "false").lower() == "true"
    base_url = os.getenv("SHINHAN_CARD_BASE_URL")

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

        # Get transactions
        result = await scraper.get_recent_transactions()

    assert result is not None
    assert isinstance(result, list)
    assert len(result) == 5  # We have 5 transactions in the fixture

    # Check first transaction structure
    first_txn = result[0]
    assert "transacted_at" in first_txn
    assert "merchant" in first_txn
    assert "amount" in first_txn
    assert "card_owner" in first_txn
    assert "installment" in first_txn
    assert "status" in first_txn

    # Verify fixture data matches
    assert first_txn["transacted_at"] == "2025.01.15 14:23"
    assert first_txn["merchant"] == "카페ABC"
    assert first_txn["amount"] == "5,500원"
    assert "본인" in first_txn["card_owner"]
    assert first_txn["installment"] == "일시불"
