"""Chart generation and access tools."""

from typing import Optional
from mcp.server.fastmcp import Context
from mcp.server.session import ServerSession
from dotenv import load_dotenv
import os

load_dotenv()

# Public chart tools (no credentials needed) - always available
def get_point_topic_public_chart_catalog(ctx: Optional[Context[ServerSession, None]] = None) -> str:
    """Get all available public charts from the Point Topic Charts API.
    
    Fetches the public chart catalog (no authentication required).
    
    Returns:
        JSON string containing public chart catalog with titles, parameters, and example URLs.
    """
    import requests
    import json
    response = requests.get("https://charts.point-topic.com/public")
    return json.dumps(response.json())


def get_point_topic_public_chart_csv(url: str, ctx: Optional[Context[ServerSession, None]] = None) -> str:
    """Get a specific public chart from Point Topic Charts API as CSV.
    
    Use this to fetch chart data for context when displaying charts.
    For iframe embedding, use URL without format parameter.
    
    Args:
        url: Chart URL WITHOUT the format parameter (e.g., no &format=png/csv).
    
    Returns: CSV string with chart data
    """
    import urllib.parse
    import requests

    # strip any existing format param and add format=csv
    parsed = urllib.parse.urlparse(url)
    query = urllib.parse.parse_qs(parsed.query)
    query.pop('format', None)
    query['format'] = 'csv'
    csv_url = urllib.parse.urlunparse(parsed._replace(query=urllib.parse.urlencode(query, doseq=True)))

    resp = requests.get(csv_url)
    if resp.status_code != 200:
        return f"Error: {resp.status_code} {resp.text}"
    
    return resp.text


# Authenticated chart tools (require API key) - TEMPORARILY DISABLED
# Uncomment the block below when the production issues are fixed

# Authenticated chart tools (require API key) - ONLY if API key present
# if has_chart_api_key:
#     # Track for status reporting
#     check_env_vars('chart_tools', ['CHART_API_KEY'])
#     def get_point_topic_chart_catalog(format_type: str = "json", ctx: Optional[Context[ServerSession, None]] = None) -> str:
#         """Get complete chart catalog with required parameters AND valid values.
        
#         CRITICAL: Check 'required_params' for EACH chart before generating URLs.
#         Most charts require 'period' - NOT optional if listed as required.
        
#         Catalog now includes valid period values for each chart.
#         Use the MOST RECENT period shown unless user specifies otherwise.
        
#         Args:
