from typing import Literal
from typing import Optional
from typing import Union
import requests
from bs4 import BeautifulSoup


def alliance_bank_withdraw(
    email: str,
    password: str,
    alliance_id: int,
    receiver: str,
    receiver_type: Literal["alliance", "nation"],
    note: Optional[str] = None,
    **resources: Union[int, float, str],
) -> bool:
    """Send money from an alliance bank.

    Parameters
    ----------
    email : str
        The email of the account to use.
    password : str
        The password of the account to use.
    alliance_id : int
        The alliance ID to send from.
    receiver : str
        The receiver of the withdrawal, must be a nation or alliance name.
    receiver_type : Literal["alliance", "nation"]
        The type of receiver, either "alliance" or "nation".
    note : Optional[str], optional
        The note to send with the withdrawal, by default no note is sent.
    **resources : Union[int, float, str]
        The resources to send, specified as kwargs. (i.e. money=100)

    Returns
    -------
    bool
        Whether or not the withdrawal was successful.
    """
    with requests.Session() as session:
        transaction_data = {f"with{key}": value for key, value in resources.items()}
        transaction_data["withtype"] = receiver_type.capitalize()
        if note is not None:
            transaction_data["withnote"] = note
        transaction_data["withrecipient"] = receiver
        transaction_data["withsubmit"] = "Withdraw"
        login_data = {
            "email": email,
            "password": password,
            "loginform": "Login",
        }
        response = session.request(
            "POST", "https://politicsandwar.com/login/", data=login_data
        )
        if "login failure" in response.text.lower():
            return False
        response = session.request(
            "POST",
            f"https://politicsandwar.com/alliance/id={alliance_id}&display=bank",
            data=transaction_data,
        )
        content = response.text
        if "Something went wrong" in content:
            transaction_data["token"] = BeautifulSoup(content, "html.parser").find("input", {"name": "token"}).attrs["value"]  # type: ignore
            response = session.request(
                "POST",
                f"https://politicsandwar.com/alliance/id={alliance_id}&display=bank",
                data=transaction_data,
            )
            content = response.text
        return "successfully transferred" in content