"""
Sample script for Shinhan Bank scraper (login through transaction fetch).
Run with `uv run scripts/shinhan_bank_sample.py` after setting the SHINHAN_* env vars.
"""

import asyncio
import json
import os
import sys
from pathlib import Path

# Allow running via `uv run scripts/shinhan_bank_sample.py` by adding project root/src to sys.path
if __package__ in (None, ""):
    project_root = Path(__file__).resolve().parent.parent
    src_path = project_root / "src"
    if str(src_path) not in sys.path:
        sys.path.insert(0, str(src_path))

from libeunhaeng.shinhan_bank_scraper import ShinhanBankScraper


def env_bool(var_name: str, default: bool = False) -> bool:
    """Parse a boolean environment variable."""
    return os.getenv(var_name, str(default)).lower() in {"1", "true", "yes", "on"}


def load_accounts(env_value: str | None) -> list[dict[str, str]]:
    """Parse SHINHAN_BANK_ACCOUNTS JSON or fall back to a single sample account."""
    if not env_value:
        return [{"number": "110-000-000000", "password": "0000"}]

    try:
        parsed = json.loads(env_value)
        if isinstance(parsed, list):
            return parsed
    except json.JSONDecodeError:
        pass

    return [{"number": "110-000-000000", "password": "0000"}]


async def main() -> None:
    base_url = os.getenv("SHINHAN_BASE_URL")
    user_id = os.getenv("SHINHAN_USER_ID", "your_user_id")
    password = os.getenv("SHINHAN_PASSWORD", "your_password")
    headless = env_bool("SHINHAN_HEADLESS")
    accounts = load_accounts(os.getenv("SHINHAN_BANK_ACCOUNTS"))

    async with ShinhanBankScraper(
        headless=headless,
        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", f"account-{account_idx + 1}")

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

            all_transactions[account_number] = transactions

    print(json.dumps(all_transactions, indent=2))


if __name__ == "__main__":
    asyncio.run(main())
