"""A product, then a whole declaration, saved, with the official Python client.

    pip install tarifftrust
    TARIFFTRUST_API_KEY=tarifftrust_... python estimate.py

Keep the API key on your server, never in a browser or a mobile app.
"""

import sys

from tarifftrust import TariffTrust


def money(amount):
    """An amount as the API gives it: a decimal string in USD, or None when unknown, never zero."""
    return "unknown" if amount is None else f"${amount}"


def describe(result):
    """Relay a result honestly: unknown is never zero, and the status always goes with it."""
    lines = [f"Status: {result.status}"]
    if result.estimated_duty is not None:
        lines.append(f"Estimated duty: {money(result.estimated_duty)}")
    elif result.status == "rate_only":
        lines.append(f"Duty rate: {result.estimated_duty_rate} of the customs value")
    for field in result.missing or []:
        # No figure until it is sent: ask your user, and send the answer where ``field`` says.
        lines.append(f"Question: {field.question} ({field.field})")
    for name, value in (result.facts or {}).items():
        # What the estimate rests on: what you sent, and the ordinary case of what you did not. Show
        # it to the user who may know better, and send their answer in ``facts``.
        lines.append(f"Rests on: {name} = {value}")
    for item in result.withheld or []:
        lines.append(f"Withheld: {item.name}: {item.reason}")
    return "\n".join(lines)


def estimate_product(client, as_of=None, facts=None):
    """``as_of`` is the date of entry; without it, the service uses today. ``facts`` are your user's own
    answers: a question is theirs to answer, never yours in their place."""
    return client.estimate(
        hts="6109.10.00.12", origin="CN", customs_value="10000", as_of=as_of, facts=facts or {}
    )


def save_declaration(client, as_of=None):
    """Ten lines of $1,000: one MPF on the declaration, not ten minimums. A retry after a timeout counts
    once and saves once: the client sends the same idempotency key on each attempt."""
    return client.estimate_entry(
        reference="Example entry",
        as_of=as_of,
        save=True,
        lines=[{"hts": "6109.10.00.12", "origin": "CN", "customs_value": "1000"} for _ in range(10)],
    )


def main():
    with TariffTrust() as client:
        print(describe(estimate_product(client)))
        saved = save_declaration(client)
        print(f"Saved estimate {saved.saved_estimate_id}")
        print(f"Duty {money(saved.estimated_duty)}, fees once: {money(saved.estimated_fees)}")
        for fee in saved.fees or []:
            print(f"  {fee.name}: {money(fee.amount)}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
