"""Makes bookshop_orders.csv: MADE-UP practice data for the Tableau guide.

Inkwell Books is not a real shop. Every customer, order and number here is
invented by this script. Standard library only. The seed is fixed, so running
it again gives the same file, row for row.

    python make_data.py
"""
import csv
import random
from datetime import date, timedelta

random.seed(2026)

PLACES = [  # (country, city, weight)
    ("Ireland", "Dublin", 14), ("Ireland", "Cork", 6), ("Ireland", "Galway", 4), ("Ireland", "Limerick", 3),
    ("United Kingdom", "London", 12), ("United Kingdom", "Manchester", 5), ("United Kingdom", "Edinburgh", 4),
    ("France", "Paris", 6), ("France", "Lyon", 2),
    ("Germany", "Berlin", 5), ("Germany", "Munich", 3),
    ("Spain", "Madrid", 3), ("Spain", "Barcelona", 3),
    ("Netherlands", "Amsterdam", 4), ("Italy", "Milan", 3), ("Portugal", "Lisbon", 2),
    ("Belgium", "Brussels", 2), ("Denmark", "Copenhagen", 2),
]

# category -> list of (product, unit price, cost as a share of price)
PRODUCTS = {
    "Fiction": [("The Salt Road", 12.99, .58), ("Harbour Lights", 10.99, .60), ("Quiet Hours", 14.99, .57), ("Paper Moons", 9.99, .62)],
    "Non-fiction": [("Small Data", 18.99, .52), ("How Rivers Bend", 16.99, .55), ("The Thrift Atlas", 21.99, .54), ("Plain Numbers", 24.99, .50)],
    "Children's": [("Otter Goes Home", 7.99, .60), ("Big Red Kite", 6.99, .63), ("Twelve Small Foxes", 8.99, .61), ("Moon for Muffin", 5.99, .64)],
    "Comics": [("Night Pilot Vol 1", 15.99, .66), ("Sky Garden", 13.99, .64), ("Iron Hare", 17.99, .88)],
    "Stationery": [("Dot Grid Notebook", 11.99, .38), ("Fineliner Set", 8.99, .42), ("Book Light", 19.99, .45), ("Bookmark Pack", 3.99, .35)],
}
CAT_WEIGHT = {"Fiction": 34, "Non-fiction": 24, "Children's": 18, "Comics": 10, "Stationery": 14}
SEGMENTS = [("Consumer", 60), ("Student", 25), ("Business", 15)]


def pick(pairs):
    items, weights = zip(*pairs)
    return random.choices(items, weights=weights)[0]


customers = []
for i in range(1, 321):
    country, city = pick([((c, t), w) for c, t, w in PLACES])
    customers.append({"id": f"C{i:04d}", "segment": pick(SEGMENTS), "country": country, "city": city,
                      "activity": random.choice([1, 1, 1, 2, 2, 3, 5])})

# Orders: 2024 and 2025, growing over time, with a December bump.
start = date(2024, 1, 1)
days = [start + timedelta(d) for d in range(731)]
day_w = [(1 + 0.6 * (d - start).days / 730) * (1.9 if d.month == 12 else 1.25 if d.month == 11 else 1.0) for d in days]

rows, line = [], 0
for o in range(1, 721):
    cust = random.choices(customers, weights=[c["activity"] for c in customers])[0]
    od = random.choices(days, weights=day_w)[0]
    ship_gap = random.randint(1, 3) if cust["segment"] == "Business" else random.randint(1, 6)
    for _ in range(random.choice([1, 1, 1, 2, 2, 3])):
        line += 1
        cat = pick(list(CAT_WEIGHT.items()))
        name, price, cost = random.choice(PRODUCTS[cat])
        units = random.choice([1, 1, 1, 2, 2, 3]) * (random.choice([2, 3, 5]) if cust["segment"] == "Business" else 1)
        disc = random.choice([0, 0, 0, 0, 0.1, 0.1, 0.2])
        if cust["segment"] == "Student":
            disc = max(disc, 0.1)
        sales = round(units * price * (1 - disc), 2)
        profit = round(sales - units * price * cost, 2)
        score = "" if random.random() < 0.42 else random.choices([1, 2, 3, 4, 5], weights=[1, 2, 5, 9, 8])[0]
        rows.append({
            "line_id": line, "order_id": f"O{o:05d}", "order_date": od.isoformat(),
            "ship_date": (od + timedelta(ship_gap)).isoformat(), "customer_id": cust["id"],
            "segment": cust["segment"], "country": cust["country"], "city": cust["city"],
            "category": cat, "product": name, "units": units, "unit_price": price, "discount": disc,
            "sales": sales, "profit": profit, "review_score": score,
            "returned": "Yes" if random.random() < 0.05 else "No",
        })

rows.sort(key=lambda r: (r["order_date"], r["order_id"], r["line_id"]))
renumber = {}
for i, r in enumerate(rows, 1):  # number orders and lines in date order
    r["line_id"] = i
    r["order_id"] = renumber.setdefault(r["order_id"], f"O{len(renumber) + 1:05d}")

with open("bookshop_orders.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=list(rows[0]))
    w.writeheader()
    w.writerows(rows)
print(len(rows), "rows written to bookshop_orders.csv")
