"""
Problem 1: Sales Data Analysis for a Retail Store
---------------------------------------------------
Reads sales data (list of dicts) and reports:
  - Total sales (revenue)
  - Average sales per product
  - Top-selling product(s) (by units sold and by revenue)
  - Sales broken down by category

Uses only core control structures: for loops, if/elif/else,
and dictionaries/lists as data types.
"""

# ---------------------------------------------------------
# Sample Sales Data
# ---------------------------------------------------------
sales_data = [
    {"product_name": "Wireless Mouse",   "category": "Electronics", "units_sold": 120, "unit_price": 499.00},
    {"product_name": "Bluetooth Speaker", "category": "Electronics", "units_sold": 75,  "unit_price": 1499.00},
    {"product_name": "Notebook",          "category": "Stationery",  "units_sold": 300, "unit_price": 40.00},
    {"product_name": "Ball Pen (Pack)",   "category": "Stationery",  "units_sold": 250, "unit_price": 60.00},
    {"product_name": "Office Chair",      "category": "Furniture",   "units_sold": 20,  "unit_price": 3500.00},
    {"product_name": "Study Table",       "category": "Furniture",   "units_sold": 15,  "unit_price": 4200.00},
    {"product_name": "LED Desk Lamp",     "category": "Electronics", "units_sold": 60,  "unit_price": 899.00},
]


def compute_revenue(product):
    """Return revenue (units_sold * unit_price) for a single product dict."""
    return product["units_sold"] * product["unit_price"]


def total_sales(data):
    """Total revenue across all products."""
    total = 0.0
    for product in data:
        total += compute_revenue(product)
    return total


def average_sales_per_product(data):
    """Average revenue per product (not per unit)."""
    if len(data) == 0:
        return 0.0
    return total_sales(data) / len(data)


def top_selling_by_units(data, top_n=3):
    """Return top_n products sorted by units_sold (descending)."""
    # Manual selection-based sort using loops (keeps it control-structure based)
    products_copy = data[:]  # shallow copy so we don't mutate original
    sorted_products = []

    while products_copy:
        best_index = 0
        for i in range(1, len(products_copy)):
            if products_copy[i]["units_sold"] > products_copy[best_index]["units_sold"]:
                best_index = i
        sorted_products.append(products_copy.pop(best_index))

    return sorted_products[:top_n]


def top_selling_by_revenue(data, top_n=3):
    """Return top_n products sorted by revenue (descending)."""
    products_copy = data[:]
    sorted_products = []

    while products_copy:
        best_index = 0
        best_revenue = compute_revenue(products_copy[0])
        for i in range(1, len(products_copy)):
            rev = compute_revenue(products_copy[i])
            if rev > best_revenue:
                best_revenue = rev
                best_index = i
        sorted_products.append(products_copy.pop(best_index))

    return sorted_products[:top_n]


def sales_by_category(data):
    """Aggregate units sold and revenue per category."""
    category_summary = {}

    for product in data:
        cat = product["category"]
        revenue = compute_revenue(product)

        if cat not in category_summary:
            category_summary[cat] = {"units_sold": 0, "revenue": 0.0}

        category_summary[cat]["units_sold"] += product["units_sold"]
        category_summary[cat]["revenue"] += revenue

    return category_summary


def print_report(data):
    print("=" * 55)
    print("SALES DATA ANALYSIS REPORT")
    print("=" * 55)

    grand_total = total_sales(data)
    avg_sales = average_sales_per_product(data)

    print(f"\nTotal Sales (Revenue): Rs. {grand_total:,.2f}")
    print(f"Average Sales per Product: Rs. {avg_sales:,.2f}")

    print("\n--- Top-Selling Products (by units sold) ---")
    for rank, product in enumerate(top_selling_by_units(data), start=1):
        print(f"{rank}. {product['product_name']} - {product['units_sold']} units")

    print("\n--- Top-Selling Products (by revenue) ---")
    for rank, product in enumerate(top_selling_by_revenue(data), start=1):
        rev = compute_revenue(product)
        print(f"{rank}. {product['product_name']} - Rs. {rev:,.2f}")

    print("\n--- Sales by Category ---")
    category_summary = sales_by_category(data)
    for cat, stats in category_summary.items():
        print(f"{cat}: {stats['units_sold']} units sold, Rs. {stats['revenue']:,.2f} revenue")

    print("=" * 55)


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