"""
Problem 3: Library Management System
---------------------------------------
Reads book/checkout data (list of dicts) and reports:
  - Total number of books
  - Number of books currently available vs checked out
  - Overdue books (due_date earlier than today)
  - Most borrowed books (using a times_borrowed counter kept per book)

Note: the base data format only tracks the CURRENT checkout state
(checked_out, due_date). To answer "most borrowed books" meaningfully,
each book also carries a running 'times_borrowed' count, which a real
system would increment every time a book is checked out.
"""

from datetime import date

# ---------------------------------------------------------
# Sample Library Data
# ---------------------------------------------------------
library_data = [
    {"title": "Clean Code", "author": "Robert C. Martin", "checked_out": True,
     "due_date": "2026-08-20", "times_borrowed": 12},
    {"title": "The Pragmatic Programmer", "author": "Andrew Hunt", "checked_out": False,
     "due_date": None, "times_borrowed": 8},
    {"title": "Introduction to Algorithms", "author": "Thomas H. Cormen", "checked_out": True,
     "due_date": "2026-09-05", "times_borrowed": 15},
    {"title": "Deep Work", "author": "Cal Newport", "checked_out": True,
     "due_date": "2026-08-10", "times_borrowed": 5},
    {"title": "Atomic Habits", "author": "James Clear", "checked_out": False,
     "due_date": None, "times_borrowed": 20},
    {"title": "Operating System Concepts", "author": "Abraham Silberschatz", "checked_out": True,
     "due_date": "2026-08-25", "times_borrowed": 9},
]

# Reference "today" for overdue calculations
TODAY = date(2026, 8, 29)


def parse_date(date_str):
    """Convert a 'YYYY-MM-DD' string into a date object."""
    year, month, day = date_str.split("-")
    return date(int(year), int(month), int(day))


def total_books(data):
    return len(data)


def available_and_checked_out(data):
    """Count how many books are available vs currently checked out."""
    available = 0
    checked_out = 0
    for book in data:
        if book["checked_out"]:
            checked_out += 1
        else:
            available += 1
    return available, checked_out


def overdue_books(data, today=TODAY):
    """Return a list of books that are checked out and past their due date."""
    overdue = []
    for book in data:
        if book["checked_out"] and book["due_date"] is not None:
            due = parse_date(book["due_date"])
            if due < today:
                overdue.append(book)
    return overdue


def most_borrowed_books(data, top_n=3):
    """Return top_n books sorted by times_borrowed (descending)."""
    books_copy = data[:]
    ranked = []

    while books_copy:
        best_index = 0
        for i in range(1, len(books_copy)):
            if books_copy[i]["times_borrowed"] > books_copy[best_index]["times_borrowed"]:
                best_index = i
        ranked.append(books_copy.pop(best_index))

    return ranked[:top_n]


def print_report(data):
    print("=" * 55)
    print("LIBRARY MANAGEMENT REPORT")
    print(f"(as of {TODAY.isoformat()})")
    print("=" * 55)

    print(f"\nTotal Books in Collection: {total_books(data)}")

    available, checked_out = available_and_checked_out(data)
    print(f"Available: {available}")
    print(f"Checked Out: {checked_out}")

    print("\n--- Overdue Books ---")
    overdue = overdue_books(data)
    if len(overdue) == 0:
        print("No overdue books.")
    else:
        for book in overdue:
            days_overdue = (TODAY - parse_date(book["due_date"])).days
            print(f"{book['title']} by {book['author']} - due {book['due_date']} "
                  f"({days_overdue} day(s) overdue)")

    print("\n--- Most Borrowed Books ---")
    for rank, book in enumerate(most_borrowed_books(data), start=1):
        print(f"{rank}. {book['title']} - borrowed {book['times_borrowed']} times")

    print("=" * 55)


if __name__ == "__main__":
    print_report(library_data)