import sys
import psycopg2 # type: ignore
import textwrap

def wrap_and_print(line, indent=' ', width=68):
    wrapped = textwrap.fill(line, width=width, initial_indent=indent, subsequent_indent=indent)
    print(wrapped)

def reformat_name(name):
    if ',' in name:
        parts = name.split(',', 1)
        return parts[1].strip() + ' ' + parts[0].strip()
    return name

def query_book_and_contributors(fk_books_value, cur):
    # Fetch title and language
    cur.execute("""
        SELECT title, lang
        FROM v_books
        WHERE fk_books = %s
        LIMIT 1;
    """, (fk_books_value,))

    result = cur.fetchone()
    if not result:
        return  # Skip if no book record found

    title_field, lang = result
    parts = title_field.split(' : $b ')
    title = parts[0].strip()
    subtitle = parts[1].strip() if len(parts) > 1 else None

    # Fetch contributors
    cur.execute("""
        SELECT role, author
        FROM v_books
        WHERE fk_books = %s
        ORDER BY role, author;
    """, (fk_books_value,))

    contributors = cur.fetchall()

    # Collect all authors and other contributors
    authors = []
    other_contributors = []
    seen_contributors = set()
    authors_original_names = []

    for role, author in contributors:
        if author in seen_contributors:
            continue
        seen_contributors.add(author)
        if role and role.lower() == 'author':
            authors.append(reformat_name(author))
            authors_original_names.append(author)
        else:
            other_contributors.append((role.title(), author))

    # Build main line content with all authors
    main_line = title
    if authors:
        if len(authors) == 1:
            authors_string = authors[0]
        else:
            authors_string = ', '.join(authors[:-1]) + " and " + authors[-1]
        main_line += ", by " + authors_string

    # Print main line, wrapping if needed
    wrapper = textwrap.TextWrapper(width=68)
    wrapped_lines = wrapper.wrap(main_line)

    if wrapped_lines:
        first_line = wrapped_lines[0]
        fk_books_str = str(fk_books_value)
        padding_space = 78 - len(first_line) - len(fk_books_str)
        if padding_space > 0:
            first_line += ' ' * padding_space + fk_books_str
        else:
            first_line += ' ' + fk_books_str

        print(first_line)
        for line in wrapped_lines[1:]:
            print(line)

    # Optional subtitle and language output
    if subtitle:
        wrap_and_print(f"[Subtitle: {subtitle}]")
    if lang and lang != "English":
        wrap_and_print(f"[Language: {lang}]")

    # Print contributors excluding authors in the byline
    for role_label, contributor in other_contributors:
        if role_label.lower() == 'author' and contributor in authors_original_names:
            continue  # Skip author shown in byline
        bracket_line = f"[{role_label}: {contributor}]"
        wrap_and_print(bracket_line)

def main():
    if len(sys.argv) != 2:
        print("Usage: python query_one_book.py <fk_book>")
        sys.exit(1)

    fk_book = int(sys.argv[1])
    ## print(f"Querying book with ID: {fk_book}")

    conn_params = {
        'host': 'localhost',
        'dbname': 'gutenberg',
        'user': 'gutenberg',
        'password': 'gutenberg-on-pglaf'
    }

    try:
        with psycopg2.connect(**conn_params) as conn:
            with conn.cursor() as cur:
                query_book_and_contributors(fk_book, cur)
    except Exception as e:
        print("Database error:", e)

if __name__ == "__main__":
    main()

