from getpass import getpass
from pathlib import Path
from akademiya import __version__, Client, constants, utils
from traceback import print_exc

# Import readline if available (Unix-like systems)
try:
    import readline  # noqa: F401
except ImportError:
    pass

base_path = Path("books")
base_path.mkdir(exist_ok=True)


def lookup_books(client: Client, name: str):
    print(f"Looking up books with the name '{name}'...")
    books = client.lookup_books(name)
    for book in books:
        print(f"Book: {book.product_title} (ID: {book.ID})")
        print(f" + Author: {book.creator_names}")


def download_book(client: Client, book_id: int):
    print(f"Fetching book with ID {book_id}...")
    book = client.get_book_info(book_id)
    print(f"Downloading book '{book.product_title}'...")
    pdf_bytes = client.get_book_pdf(book)
    if pdf_bytes is None:
        print("The server didn't return any PDF data.")
        return
    constants.PLATFORM_DIRS.site_cache_path.mkdir(parents=True, exist_ok=True)
    temp_path = constants.PLATFORM_DIRS.site_cache_path / f"{book.ID}.pdf"
    pdf_path = base_path / f"{book.ID}.pdf"
    with temp_path.open("wb") as f:
        f.write(pdf_bytes)
    print("Decrypting book...")
    utils.decrypt_book_file(temp_path, pdf_path)
    print(f"Book downloaded to '{pdf_path.resolve()}'")


def borrow_book(client: Client, book_id: int):
    print(f"Borrowing book with ID {book_id}...")
    if client.is_borrowing(book_id=book_id):
        print("You are already borrowing this book.")
        return
    client.borrow_book(book_id)
    print("Book borrowed successfully.")


def user_info(client: Client):
    print(f"User ID: {client.user.id}")
    print(f"Username: {client.user.username}")
    print(f"Full Name: {client.user.full_name}")
    print(f"Avatar URL: {client.user.avatar_url}")
    print(f"Token: {client.user.token}")


def main():
    print(
        f"Akademiya CLI v{__version__} - https://git.tretrauit.me/tretrauit/akademiya"
    )
    print("Welcome to Akademiya CLI, an unofficial client for a book library.")
    print(
        "This client is no way affiliated with the official client itself, and should be used for educational purposes only."
    )
    client = Client()
    print()
    print("Authorization is required to access the library.")
    username = input("Username: ")
    password = getpass("Password (doesn't show on the console): ")
    try:
        client.login(username, password)
    except Exception as e:
        print(f"An error occurred while logging in: {e}")
        return
    print(f"Logged in as {client.user.full_name} (ID: {client.user.id})")
    print("Type 'help' for a list of available commands.")
    # Very simple command handling but idgaf.
    while True:
        try:
            command_str = input("> ")
            base_command = command_str.split(" ", 1)[0]
            match base_command:
                case "exit":
                    print("Exiting...")
                    break
                case "help":
                    print("Available commands:")
                    print("exit - Exits the program")
                    print("help - Shows this help message")
                    print("lookup <book name> - Lookup books by name")
                    print("download <book ID> - Download a book by ID")
                    print("borrow <book ID> - Borrow a book by ID")
                    print("userinfo - Show the current user information")
                case "lookup":
                    _, name = command_str.split(" ", 1)
                    lookup_books(client, name)
                case "download":
                    _, book_id = command_str.split(" ", 1)
                    download_book(client, int(book_id))
                case "borrow":
                    _, book_id = command_str.split(" ", 1)
                    borrow_book(client, int(book_id))
                case "userinfo":
                    user_info(client)
                case _:
                    print(
                        "Unknown command, type 'help' for a list of available commands."
                    )
        except KeyboardInterrupt:
            print("Exiting...")
            break
        except Exception:
            print("An error occurred while executing the provided command.")
            print_exc()


if __name__ == "__main__":
    main()
