"""MCP Resources for Meta Ads MCP Server.

Exposes Meta Ads data as MCP Resources for AI assistants to access.
Resources provide read-only access to account information, API status,
and common reference data.

MCP SDK v1.x Feature: Resources decorator for structured data access.
"""
from __future__ import annotations

from typing import TYPE_CHECKING

from mcp.server.fastmcp import FastMCP

from .logging import get_logger
from .meta_client import get_client

if TYPE_CHECKING:
    pass

logger = get_logger(__name__)


def register_resources(mcp: FastMCP) -> None:
    """Register all MCP resources with the server."""

    @mcp.resource("meta://api/info")
    async def get_api_info() -> str:
        """Get Meta Marketing API version and status information.
        
        Returns current API version, rate limit status, and health info.
        """
        try:
            client = get_client()
            
            # Get API debug info
            response = await client.get("debug_token", params={
                "input_token": client.access_token,
            })
            
            return f"""Meta Marketing API Information
================================
API Version: {client.version}
Base URL: {client.base_url}
Token Status: Valid
Scopes: {', '.join(response.get('data', {}).get('scopes', []))}
"""
        except Exception as e:
            return f"Error fetching API info: {str(e)}"

    @mcp.resource("meta://v24/breaking-changes")
    async def get_v24_breaking_changes() -> str:
        """Get summary of Meta Marketing API v24.0 breaking changes.
        
        Critical information for v24.0 compliance.
        """
        return """Meta Marketing API v24.0 Breaking Changes (October 2025)
=========================================================

1. ADVANTAGE+ CAMPAIGNS MIGRATION (CRITICAL)
   - Advantage+ Shopping Campaigns (ASC) creation DEPRECATED
   - Advantage+ App Campaigns (AAC) creation DEPRECATED
   - Use unified Advantage+ Campaigns via migrate_to_advantage_plus
   
2. FLAGGED RESOURCES - UPDATE FAILURES
   - Flagged custom audiences now FAIL on update
   - Flagged custom conversions now FAIL on update
   - Use meta.audience.check_flagged before audience updates
   - Use meta.conversion.check_flagged before conversion updates
   
3. BUDGET SHARING - NEW REQUIRED FIELD
   - is_adset_budget_sharing_enabled REQUIRED for ad set budgets
   - Set to true for budget sharing between ad sets
   - Daily budget flexibility increased to +/-75%

4. LOOKALIKE AUDIENCES - STRICT VALIDATION
   - lookalike_spec field now requires valid subfields
   - Use meta.lookalike.validate_spec before creation

5. PLACEMENTS - DEPRECATIONS
   - Facebook video feeds placement DEPRECATED
   - Use Facebook Reels placement instead
   - placement_soft_opt_out: Allocate up to 5% to excluded placements

6. ADVANTAGE+ CATALOG ADS
   - dynamic_media_default should be explicitly set on eligible flows

7. CTMLG API DEPRECATION
   - Migrate CTMLG dependencies to supported replacement APIs
   - Audit legacy calls before deploying new campaign workflows

8. CATALOG BATCH API
   - 30MB payload size limit enforced
   - allow_upsert flag now supported

Resolution Resources:
- Flagged audiences: https://www.facebook.com/business/help/1055828013359808
- Flagged conversions: https://www.facebook.com/business/help/2455915321411996
- Migration guide: https://developers.facebook.com/docs/marketing-api/advantage-campaigns
"""

    @mcp.resource("meta://tools/categories")
    async def get_tool_categories() -> str:
        """Get list of tool categories available in Meta Ads MCP Server."""
        return """Meta Ads MCP Server Tool Categories
====================================

CORE OPERATIONS
- meta.graph.request - Raw Graph API access
- meta.ads.insights - Metrics and statistics
- meta.ads.create/update/delete - CRUD operations
- meta.ads.batch - Bulk operations

CAMPAIGN MANAGEMENT (15 tools)
- Campaign lifecycle (create, update, delete, duplicate)
- Budget management
- Template operations

AD SET & AD MANAGEMENT (12 tools)
- Targeting configuration
- Bid strategy
- Creative linking

AUDIENCE INTELLIGENCE (12+ tools)
- Custom audiences
- Lookalike audiences  
- Audience overlap analysis
- [v24.0+] Flagged audience checks

CREATIVE & CONTENT (20+ tools)
- Asset management
- AI text generation
- Video/Reels optimization

CONVERSION & ATTRIBUTION (15+ tools)
- Funnel analysis
- Path analysis
- [v24.0+] Flagged conversion checks

FRAUD DETECTION & SECURITY (5 tools)
- Bot detection
- Invalid traffic filtering
- Account security monitoring

EXECUTIVE REPORTING (6 tools)
- CEO/CFO dashboards
- Board presentations
- P&L analysis

TACTICAL OPERATIONS (10 tools)
- Real-time performance
- Health monitoring
- Budget burn rate

Total: 492+ enterprise-grade tools
"""

    @mcp.resource("meta://account/{account_id}/summary")
    async def get_account_summary(account_id: str) -> str:
        """Get summary information for an ad account.
        
        Args:
            account_id: Ad account ID (e.g., act_123456789)
        """
        try:
            client = get_client()
            
            # Ensure account_id has act_ prefix
            if not account_id.startswith("act_"):
                account_id = f"act_{account_id}"
            
            response = await client.get(account_id, params={
                "fields": "id,name,account_status,currency,timezone_name,spend_cap,amount_spent"
            })
            
            status_map = {
                1: "ACTIVE",
                2: "DISABLED", 
                3: "UNSETTLED",
                7: "PENDING_RISK_REVIEW",
                9: "IN_GRACE_PERIOD",
                100: "PENDING_CLOSURE",
                101: "CLOSED",
            }
            
            status_code = response.get("account_status", 0)
            status = status_map.get(status_code, f"UNKNOWN ({status_code})")
            
            return f"""Ad Account Summary
==================
ID: {response.get('id', account_id)}
Name: {response.get('name', 'Unknown')}
Status: {status}
Currency: {response.get('currency', 'USD')}
Timezone: {response.get('timezone_name', 'Unknown')}
Spend Cap: {response.get('spend_cap', 'Not set')}
Amount Spent: {response.get('amount_spent', '0')}
"""
        except Exception as e:
            return f"Error fetching account {account_id}: {str(e)}"


    logger.info("Registered MCP resources")
