"""Shelley Inventory tools — tonewood inventory scraping, search, and analytics."""

import csv
import os
from pathlib import Path

from mentorr.helpers import get_user_data_dir


def register(mcp):
    """Register all Shelley Inventory tools on the given FastMCP instance."""

    @mcp.tool()
    def update_shelley_inventory() -> str:
        """
        Triggers the Shelley Hardwoods scraper (10,000 item limit) and syncs to the Master Sheet.
        Use this when you want to refresh data from Shelley.
        """
        from mentorr.pipeline import scrape_shelley, sync_master
        from mentorr.pipeline.upload_sheets import run_if_configured

        data_dir = str(get_user_data_dir())

        scrape_out = scrape_shelley.run(data_dir, limit=10000)
        sync_out = sync_master.run(data_dir)
        upload_out = run_if_configured(
            str(Path(data_dir) / "processed" / "master_inventory.csv"),
            worksheet="Shelley",
        )

        return f"Scrape Output:\n{scrape_out}\n\nSync Output:\n{sync_out}\n\nUpload Output:\n{upload_out}"

    @mcp.tool()
    def update_exotic_inventory() -> str:
        """
        Triggers the Exotic Wood Zone scraper (5,000 item limit) and syncs to the Master Sheet.
        Use this when you want to refresh data from Exotic Wood Zone.
        """
        from mentorr.pipeline import scrape_exoticwoodzone, sync_master
        from mentorr.pipeline.upload_sheets import run_if_configured

        data_dir = str(get_user_data_dir())

        scrape_out = scrape_exoticwoodzone.run(data_dir, limit=5000)
        sync_out = sync_master.run(data_dir)
        upload_out = run_if_configured(
            str(Path(data_dir) / "processed" / "master_inventory.csv"),
            worksheet="Shelley",
        )

        return f"Scrape Output:\n{scrape_out}\n\nSync Output:\n{sync_out}\n\nUpload Output:\n{upload_out}"

    @mcp.tool()
    def update_stewmac_inventory() -> str:
        """
        Triggers the StewMac scraper (sitemap based) and syncs to the Master Sheet.
        Use this when you want to refresh data from StewMac.
        """
        from mentorr.pipeline import scrape_stewmac, sync_master
        from mentorr.pipeline.upload_sheets import run_if_configured

        data_dir = str(get_user_data_dir())

        scrape_out = scrape_stewmac.run(data_dir)
        sync_out = sync_master.run(data_dir)
        upload_out = run_if_configured(
            str(Path(data_dir) / "processed" / "master_inventory.csv"),
            worksheet="Shelley",
        )

        return f"Scrape Output:\n{scrape_out}\n\nSync Output:\n{sync_out}\n\nUpload Output:\n{upload_out}"

    @mcp.tool()
    def process_lab_inbox() -> str:
        """
        Scans 'lab_inbox' for images (receipts/photos), uses AI to extract inventory items,
        and adds them to the Master Sheet as 'Shelley Lab (Stock)'.
        """
        from mentorr.pipeline import ingest_lab, sync_master
        from mentorr.pipeline.upload_sheets import run_if_configured

        data_dir = str(get_user_data_dir())

        ingest_out = ingest_lab.run(data_dir)
        sync_out = sync_master.run(data_dir)
        upload_out = run_if_configured(
            str(Path(data_dir) / "processed" / "master_inventory.csv"),
            worksheet="Shelley",
        )

        return f"Ingestion Output:\n{ingest_out}\n\nSync Output:\n{sync_out}\n\nUpload Output:\n{upload_out}"

    @mcp.tool()
    def get_inventory_stats() -> str:
        """
        Returns summary statistics of the current Master Inventory (counts by Seller and Species).
        """
        master_path = get_user_data_dir() / "processed" / "master_inventory.csv"
        if not master_path.exists():
            return "Master inventory file not found. Run an inventory update first."

        seller_counts = {}
        species_counts = {}
        total = 0

        with open(str(master_path), "r", encoding="utf-8") as f:
            reader = csv.DictReader(f)
            for row in reader:
                if row.get("status") == "Active":
                    total += 1
                    seller = row.get("seller", "Unknown")
                    species = row.get("species", "Unknown")
                    seller_counts[seller] = seller_counts.get(seller, 0) + 1
                    species_counts[species] = species_counts.get(species, 0) + 1

        stats = f"Total Active Items: {total}\n\nBy Seller:\n"
        for s, c in seller_counts.items():
            stats += f"- {s}: {c}\n"

        stats += "\nTop 10 Species:\n"
        sorted_species = sorted(species_counts.items(), key=lambda x: x[1], reverse=True)[:10]
        for s, c in sorted_species:
            stats += f"- {s}: {c}\n"

        return stats

    @mcp.tool()
    def search_inventory(query: str, limit: int = 10) -> str:
        """
        Searches the Master Inventory for items matching the query string (case-insensitive).
        Returns the top 'limit' matching items.
        """
        master_path = get_user_data_dir() / "processed" / "master_inventory.csv"
        if not master_path.exists():
            return "Master inventory file not found. Run an inventory update first."

        matches = []
        query_lower = query.lower()

        with open(str(master_path), "r", encoding="utf-8") as f:
            reader = csv.DictReader(f)
            for row in reader:
                if row.get("status") != "Active":
                    continue
                content = f"{row.get('name', '')} {row.get('species', '')} {row.get('raw_attributes', '')}".lower()
                if query_lower in content:
                    matches.append(row)
                    if len(matches) >= limit:
                        break

        if not matches:
            return "No matching items found."

        result = f"Found {len(matches)} matches for '{query}':\n"
        for item in matches:
            result += f"- [{item.get('seller', '?')}] {item.get('name', '?')} ({item.get('species', '?')}) - {item.get('price', '?')}\n"
            result += f"  Link: {item.get('link', 'N/A')}\n"

        return result
