import csv
from datetime import date, timedelta
from pathlib import Path
from agents import function_tool

SALES = Path(__file__).parent.parent / "raw_data" / "sales.csv"

@function_tool
def sales_by_branch(days: int, title: str = "") -> dict:
    """Copies sold per branch over the last N days, for all titles or one title."""
    if days < 1:
        return {"error": "days must be a positive number."}
    with SALES.open(newline="") as f:
        rows = list(csv.DictReader(f))
    if title and not any(r["title"] == title for r in rows):
        return {"error": f"No sales records for {title}."}
    last = max(date.fromisoformat(r["date"]) for r in rows)
    since = last - timedelta(days=days - 1)
    totals = {}
    for r in rows:
        if date.fromisoformat(r["date"]) >= since and (not title or r["title"] == title):
            totals[r["branch"]] = totals.get(r["branch"], 0) + int(r["copies"])
    return {"from": since.isoformat(), "to": last.isoformat(), "copies_sold": totals}
