"""DuckieDai Frustum Volume for TI-84 Plus CE Python."""

from math import sqrt


def duckiedai_intro(program_name, wait=True):
    """Show the reusable DuckieDai program opening."""
    title = program_name[:16]
    empty = 16 - len(title)
    left = empty // 2
    right = empty - left

    print("+----------------------+")
    print("|   " + " " * left + title + " " * right + "   |")
    print("|                      |")
    print("|       __             |")
    print("|   ___(o )>  quack!   |")
    print("|   \\ <_. )           |")
    print("|    `---'             |")
    print("|     by DuckieDai     |")
    print("+----------------------+")
    print("Loading...")

    if wait:
        input("Press enter to start ")
        print("\n" * 6)


def positive_number(prompt):
    """Require a positive finite number."""
    while True:
        try:
            value = float(input(prompt))

            if value > 0 and value < 1e100:
                return value

        except ValueError:
            pass

        print("Enter a number above 0.")


def show_answer(name, value, unit):
    print()
    print("ANSWER")
    print(name + " = " + str(value))
    print(unit)


def frustum_volume(h, a1, a2):
    """Calculate frustum volume."""
    return (
        h / 3 *
        (a1 + a2 + sqrt(a1 * a2))
    )


def solve_missing_area(volume, height, known_area):
    """Solve one base area when the other is known."""

    k = 3 * volume / height

    inside = 4 * k - 3 * known_area

    if inside < 0:
        return None

    root_area = (
        -sqrt(known_area) +
        sqrt(inside)
    ) / 2

    if root_area < 0:
        return None

    return root_area ** 2


def main():
    duckiedai_intro("FRUSTUM VOLUME")

    print("FRUSTUM VOLUME")
    print()
    print("V = h/3 *")
    print("(A1+A2+sqrt(A1*A2))")
    print()
    print("A1 = base area 1")
    print("A2 = base area 2")
    print("h  = height")
    print()
    print("What do you need?")
    print()
    print("1. Volume")
    print("2. Height")
    print("3. Base area A1")
    print("4. Base area A2")
    print()

    choice = input("Choose 1-4: ")

    print()

    # ==========================================
    # 1. SOLVE VOLUME
    #
    # V = h/3(A1+A2+sqrt(A1*A2))
    # ==========================================

    if choice == "1":

        h = positive_number(
            "Height: "
        )

        a1 = positive_number(
            "Base area A1: "
        )

        a2 = positive_number(
            "Base area A2: "
        )

        volume = frustum_volume(
            h, a1, a2
        )

        print()
        print("Using:")
        print("V = h/3 *")
        print("(A1+A2+sqrt(A1*A2))")

        show_answer(
            "Volume",
            volume,
            "cubic units"
        )

    # ==========================================
    # 2. SOLVE HEIGHT
    #
    # h = 3V /
    # (A1+A2+sqrt(A1*A2))
    # ==========================================

    elif choice == "2":

        volume = positive_number(
            "Volume: "
        )

        a1 = positive_number(
            "Base area A1: "
        )

        a2 = positive_number(
            "Base area A2: "
        )

        denominator = (
            a1 +
            a2 +
            sqrt(a1 * a2)
        )

        h = (
            3 * volume /
            denominator
        )

        print()
        print("Using:")
        print("V = h/3 *")
        print("(A1+A2+sqrt(A1*A2))")
        print()
        print("Rearranged:")
        print("h = 3V /")
        print("(A1+A2+sqrt(A1*A2))")

        show_answer(
            "Height",
            h,
            "units"
        )

    # ==========================================
    # 3. SOLVE A1
    # ==========================================

    elif choice == "3":

        volume = positive_number(
            "Volume: "
        )

        h = positive_number(
            "Height: "
        )

        a2 = positive_number(
            "Known area A2: "
        )

        a1 = solve_missing_area(
            volume,
            h,
            a2
        )

        if a1 is None:

            print()
            print("NO VALID RESULT")
            print()
            print("Check volume,")
            print("height, and area.")

        else:

            print()
            print("Using:")
            print("V = h/3 *")
            print("(A1+A2+sqrt(A1*A2))")
            print()
            print("Solved for A1.")

            show_answer(
                "A1",
                a1,
                "square units"
            )

    # ==========================================
    # 4. SOLVE A2
    # ==========================================

    elif choice == "4":

        volume = positive_number(
            "Volume: "
        )

        h = positive_number(
            "Height: "
        )

        a1 = positive_number(
            "Known area A1: "
        )

        a2 = solve_missing_area(
            volume,
            h,
            a1
        )

        if a2 is None:

            print()
            print("NO VALID RESULT")
            print()
            print("Check volume,")
            print("height, and area.")

        else:

            print()
            print("Using:")
            print("V = h/3 *")
            print("(A1+A2+sqrt(A1*A2))")
            print()
            print("Solved for A2.")

            show_answer(
                "A2",
                a2,
                "square units"
            )

    else:
        print("Invalid choice.")

    print()
    print("DuckieDai says: done!")


# TI-Python imports the selected AppVar rather than
# setting __name__ to main.
main()
