"""Batch download MCP tools for YFinance.

This module provides tools for batch downloading data for multiple tickers.
"""

import yfinance as yf
from typing import List, Optional
from mcp.server.fastmcp import FastMCP

from ..utils.serializers import df_to_json, dict_to_json


def register(mcp: FastMCP):
    """Register all batch-related tools with the MCP server."""

    @mcp.tool()
    def download(
        symbols: List[str],
        period: str = "1mo",
        interval: str = "1d",
        start: Optional[str] = None,
        end: Optional[str] = None,
        group_by: str = "column"
    ) -> dict:
        """Download historical price data for multiple stocks at once.
        
        This is more efficient than calling get_price_history multiple times
        when you need data for many stocks.
        
        Args:
            symbols: List of ticker symbols (e.g., ["AAPL", "MSFT", "GOOGL"])
            period: Data period - 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
            interval: Data interval - 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo
            start: Start date in YYYY-MM-DD format (overrides period)
            end: End date in YYYY-MM-DD format
            group_by: How to group the data - "column" or "ticker"
            
        Returns:
            Historical OHLCV data for all requested symbols
        """
        df = yf.download(
            tickers=symbols,
            period=period,
            interval=interval,
            start=start,
            end=end,
            group_by=group_by,
            progress=False  # Disable progress bar for MCP
        )
        
        return df_to_json(df)

    @mcp.tool()
    def get_tickers_info(symbols: List[str]) -> dict:
        """Get basic information for multiple stocks at once.
        
        Args:
            symbols: List of ticker symbols (e.g., ["AAPL", "MSFT", "GOOGL"])
            
        Returns:
            Dictionary with symbol as key and info dict as value
        """
        result = {}
        for symbol in symbols:
            try:
                ticker = yf.Ticker(symbol)
                fast_info = ticker.fast_info
                result[symbol] = {
                    "currency": fast_info.get("currency"),
                    "exchange": fast_info.get("exchange"),
                    "market_cap": fast_info.get("market_cap"),
                    "last_price": fast_info.get("last_price"),
                    "previous_close": fast_info.get("previous_close"),
                    "fifty_day_average": fast_info.get("fifty_day_average"),
                    "two_hundred_day_average": fast_info.get("two_hundred_day_average"),
                }
            except Exception as e:
                result[symbol] = {"error": str(e)}
        
        return result
