"""
Automated Sales Report Generator
by Christian Sesay - Sierra Leone

Reads a CSV of raw sales rows and automatically generates a
plain-text summary report - total revenue, best-selling item,
and average sale value. Saves a business the time of doing this
by hand every week.
Built for the Google IT Automation with Python Certificate.

Expected CSV columns: item,quantity,price
"""

import csv
from collections import defaultdict


def generate_report(csv_path, output_path="sales_report.txt"):
    totals_by_item = defaultdict(float)
    quantities_by_item = defaultdict(int)
    total_revenue = 0.0
    total_sales = 0

    with open(csv_path, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            item = row["item"].strip()
            quantity = int(row["quantity"])
            price = float(row["price"])
            line_total = quantity * price

            totals_by_item[item] += line_total
            quantities_by_item[item] += quantity
            total_revenue += line_total
            total_sales += 1

    if total_sales == 0:
        print("No sales rows found in that file.")
        return

    best_seller = max(totals_by_item, key=totals_by_item.get)
    average_sale = total_revenue / total_sales

    lines = []
    lines.append("=" * 50)
    lines.append("SALES SUMMARY REPORT")
    lines.append("=" * 50)
    lines.append(f"Total transactions: {total_sales}")
    lines.append(f"Total revenue: ${total_revenue:,.2f}")
    lines.append(f"Average sale value: ${average_sale:,.2f}")
    lines.append(f"Best-selling item: {best_seller} (${totals_by_item[best_seller]:,.2f} total)")
    lines.append("")
    lines.append("Revenue by item:")
    for item, total in sorted(totals_by_item.items(), key=lambda x: x[1], reverse=True):
        lines.append(f"  {item:<20} {quantities_by_item[item]:>4} sold   ${total:,.2f}")

    report = "\n".join(lines)
    print("\n" + report)

    with open(output_path, "w", encoding="utf-8") as f:
        f.write(report)
    print(f"\nSaved to {output_path}")


if __name__ == "__main__":
    print("=" * 60)
    print("AUTOMATED SALES REPORT GENERATOR")
    print("by Christian Sesay - Sierra Leone")
    print("=" * 60)
    path = input("\nEnter the path to your sales CSV file → ").strip()
    generate_report(path)
