"""
Fixture-driven end-to-end test that runs ShinhanBankScraper.main() against local HTML.
Ensures the scraper returns parsed transaction history when pointed at fixtures.
"""

import json
import os
from pathlib import Path

import pytest

from libeunhaeng.shinhan_bank_scraper import ShinhanBankScraper


@pytest.fixture
def base_fixture_url(tmp_path_factory):
    fixtures_root = Path(__file__).parent / "fixtures" / "shinhan_bank"
    # Use the login page as the base URL; scraper will follow in-page links
    return f"file://{fixtures_root / 'login_page.html'}"


@pytest.fixture
def fixtures_root():
    return Path(__file__).parent / "fixtures" / "shinhan_bank"


@pytest.fixture
def account_page_url(fixtures_root):
    return f"file://{fixtures_root / 'account_page.html'}"


@pytest.fixture
def transaction_history_url(fixtures_root):
    return f"file://{fixtures_root / 'transaction_history.html'}"


@pytest.mark.asyncio
async def test_enter_user_id_updates_login_field(base_fixture_url):
    async with ShinhanBankScraper(headless=True, base_url=base_fixture_url) as scraper:
        await scraper.navigate_to_login()
        await scraper.enter_user_id("fixture_user")

        filled_value = await scraper.page.evaluate('document.getElementById("ibx_loginId").value')
        assert filled_value == "fixture_user"


@pytest.mark.asyncio
async def test_enter_password_via_keyboard_types_password(base_fixture_url):
    async with ShinhanBankScraper(headless=True, base_url=base_fixture_url) as scraper:
        await scraper.navigate_to_login()
        await scraper.enter_password_via_keyboard("abc@123")

        masked_field = await scraper.page.evaluate('document.getElementById("비밀번호").value')

        assert masked_field == "*" * len("abc@123")


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

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


@pytest.mark.asyncio
async def test_navigate_to_transaction_history(account_page_url):
    async with ShinhanBankScraper(headless=True) as scraper:
        await scraper.page.goto(account_page_url, wait_until="domcontentloaded")
        navigated = await scraper.navigate_to_transaction_history()

        assert navigated is True
        assert "transaction_history.html" in scraper.page.url


@pytest.mark.asyncio
async def test_get_transactions_parses_rows(monkeypatch, transaction_history_url):
    async with ShinhanBankScraper(headless=True) as scraper:
        await scraper.page.goto(transaction_history_url, wait_until="domcontentloaded")

        async def stay_on_transaction_page():
            return True

        monkeypatch.setattr(scraper, "navigate_to_transaction_history", stay_on_transaction_page)

        transactions = await scraper.get_transactions(
            account_index=0,
            account_password="1234",
        )

        assert len(transactions) == 3
        assert transactions[0]["description"] == "ATM출금"
        assert transactions[0]["withdrawal_amount"] == "50,000"
        assert transactions[1]["deposit_amount"] == "100,000"
        assert transactions[2]["branch"] == "서울지점"
        assert transactions[0]["transaction_kind"] == "출금"
        assert " " in transactions[0]["transacted_at"]


@pytest.mark.asyncio
async def test_main_returns_transactions_from_fixtures(monkeypatch, base_fixture_url):
    """
    Runs asyncio.main with fixture base URL and asserts transactions are parsed.
    """
    # Point scraper to local fixtures and headless mode
    monkeypatch.setenv("SHINHAN_BASE_URL", base_fixture_url)
    monkeypatch.setenv("SHINHAN_HEADLESS", "true")
    monkeypatch.setenv("SHINHAN_USER_ID", "fixture_user")
    monkeypatch.setenv("SHINHAN_PASSWORD", "test@123")
    monkeypatch.setenv("SHINHAN_BANK_ACCOUNTS", '[{"number":"110-123-456789","password":"1234"}]')

    # Emulate main() logic
    user_id = os.getenv("SHINHAN_USER_ID")
    password = os.getenv("SHINHAN_PASSWORD")
    accounts_json = os.getenv("SHINHAN_BANK_ACCOUNTS")
    headless_env = os.getenv("SHINHAN_HEADLESS", "false").lower() == "true"
    base_url = os.getenv("SHINHAN_BASE_URL")

    accounts = json.loads(accounts_json)

    async with ShinhanBankScraper(
        headless=headless_env,
        base_url=base_url,
    ) as scraper:
        # Login
        await scraper.login(user_id, password)

        # Fetch transactions for each account
        all_transactions = {}

        for account_idx, account_config in enumerate(accounts):
            account_password = account_config.get("password")
            account_number = account_config.get("number")

            transactions = await scraper.get_transactions(account_index=account_idx, account_password=account_password)

            all_transactions[account_number] = transactions

        result = all_transactions

    assert isinstance(result, dict)
    assert "110-123-456789" in result
    transactions = result["110-123-456789"]
    assert len(transactions) == 3
    assert transactions[0]["description"] == "ATM출금"
    assert transactions[0]["withdrawal_amount"] == "50,000"
    assert transactions[1]["deposit_amount"] == "100,000"
    assert transactions[2]["branch"] == "서울지점"
