from datetime import date
from decimal import Decimal
from pathlib import Path

import click
from moneyed import Currency, Money, list_all_currencies

from hledger_tools.resources import Loan, parse_journal


@click.group
def cli():
    pass


@cli.command
def list_currencies():
    def get_symbol(currency: Currency):
        string = str(currency.zero)
        return string[: string.find("0")]

    for currency in list_all_currencies():
        click.echo(f"{currency} {get_symbol(currency)}")


@cli.command
@click.argument("output")
@click.option(
    "--early_payments_journal",
    "-e",
    type=click.Path(),
    default=None,
    help="Path to Early Payments Journal",
)
def loan_journal(output: str, early_payments_journal: Path | None = None):
    # need to get a bunch of information from the user
    loan_name = click.prompt(text="Loan Description", type=click.STRING)
    loan_begin_args = click.prompt(text="Beginning Date (YYYY-MM-DD)", type=click.STRING).split("-")
    loan_begin = date(int(loan_begin_args[0]), int(loan_begin_args[1]), int(loan_begin_args[2]))
    term_months = click.prompt(text="Loan Term in Months", type=click.INT)
    annual_interest = round(Decimal(click.prompt(text="Annual Interest Rate (ex: 0.02)", type=click.FLOAT)), 7)
    currency = click.prompt(text="Currency Code", type=click.STRING)
    principal = Money(click.prompt(text="Loan Amount", type=click.FLOAT), currency)

    cash = click.prompt(text="Cash Account", type=click.STRING).split(":")
    expense = click.prompt(text="Interest Expense Account", type=click.STRING).split(":")
    liability = click.prompt(text="Liability Account", type=click.STRING).split(":")

    loan = Loan(
        name=loan_name,
        begin=loan_begin,
        term_months=term_months,
        annual_interest=annual_interest,
        principal=principal,
    )

    if early_payments_journal:
        loan.early_payments = parse_journal(Path(early_payments_journal))

    entries = [entry for entry in loan.get_entries(cash=cash, expense=expense, liability=liability)]

    click.echo()

    for entry in entries[:2]:
        click.echo(entry.to_str)
        click.echo()

    click.echo("-------hidden payments-------")
    print()

    for entry in entries[-2:]:
        click.echo(entry.to_str)
        click.echo()

    path = Path(output)

    results = [entry.to_str for entry in entries]
    path.write_text("\n\n".join(results))
