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

import click
from moneyed import Money

from hledger_tools.make_loan_entries import make_loan_entries
from hledger_tools.resources import Entry, Loan, Mark, Posting

DEFAULT_CURRENCY = "USD"


@click.group
def cli():
    pass


@cli.command
@click.argument("output")
def loan_journal_entries(output: str):
    # 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 Years", type=click.INT) * 12
    annual_interest = round(Decimal(click.prompt(text="Annual Interest Rate (ex: 0.02)", type=click.FLOAT)), 3)
    principal = Money(click.prompt(text="Loan Amount", type=click.FLOAT), DEFAULT_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,
    )

    postings = [
        Posting(account=cash, amount=loan.principal, comment=""),
        Posting(account=liability, amount=loan.principal * -1, comment=""),
    ]
    initial_entry = Entry(
        date=loan_begin,
        code="",
        status=Mark.UNMARKED,
        description=f"Opening Loan: {loan.principal}",
        comment="Opening Loan",
        postings=postings,
    )

    entries = [initial_entry]
    entries.extend(make_loan_entries(loan=loan, cash=cash, expense=expense, liability=liability))
    results = [entry.to_str for entry in entries]

    click.echo()
    click.echo(loan)
    click.echo()

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

    click.echo()
    click.echo(".")
    click.echo(".")
    click.echo(".")
    click.echo()

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

    path = Path(output)
    path.write_text("\n\n\n".join(results))
