"""Sync raw scraper CSVs into a single master inventory."""

import csv
import os
from datetime import date
from pathlib import Path
from typing import Dict, List


SOURCES = [
    {"filename": "shelley_latest.csv", "seller": "Shelley Hardwoods"},
    {"filename": "ebay_latest.csv", "seller": "Shabby Chic Guitars"},
    {"filename": "exoticwood_latest.csv", "seller": "Exotic Wood Zone"},
    {"filename": "stewmac_latest.csv", "seller": "StewMac"},
    {"filename": "shelley_lab.csv", "seller": "Shelley Lab (Stock)"},
]


def _load_csv(path: str) -> Dict[str, Dict[str, str]]:
    if not os.path.exists(path):
        return {}
    with open(path, "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        return {row["id"]: row for row in reader if "id" in row}


def run(data_dir: str) -> str:
    """Sync all raw CSVs in data_dir/raw/ into data_dir/processed/master_inventory.csv."""
    data_path = Path(data_dir)
    master_path = data_path / "processed" / "master_inventory.csv"
    raw_dir = data_path / "raw"

    master_db = _load_csv(str(master_path))
    today = date.today().isoformat()
    updated_master = dict(master_db)

    messages = []

    for source in SOURCES:
        path = raw_dir / source["filename"]
        seller_name = source["seller"]

        if not path.exists():
            continue

        latest_db = _load_csv(str(path))
        if not latest_db:
            continue

        messages.append(f"Processing {seller_name} ({len(latest_db)} items)")

        for item_id, item in latest_db.items():
            if item_id in updated_master:
                existing = updated_master[item_id]
                item["listed_date"] = existing.get("listed_date", today)
            else:
                item["listed_date"] = today

            item["last_seen"] = today
            item["status"] = "Active"
            updated_master[item_id] = item

        for item_id, item in master_db.items():
            if item.get("seller") == seller_name:
                if item_id not in latest_db:
                    updated_master[item_id]["status"] = "Sold/Removed"

    if updated_master:
        sorted_rows = sorted(updated_master.values(), key=lambda x: x.get("listed_date", ""), reverse=True)
        keys = list(sorted_rows[0].keys())

        master_path.parent.mkdir(parents=True, exist_ok=True)
        with open(str(master_path), "w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=keys)
            writer.writeheader()
            writer.writerows(sorted_rows)
        messages.append(f"Master Sheet updated: {len(updated_master)} total items.")
    else:
        messages.append("No data to write.")

    return "\n".join(messages)


if __name__ == "__main__":
    import sys
    data_dir = sys.argv[1] if len(sys.argv) > 1 else "."
    print(run(data_dir))
