from typing import Any, Dict, Optional, Union
import aiohttp
import logging
from app.services.external_api.base_external_service import BaseExternalService
from app.services.external_api.tcgplayer.tcgplayer_credentials import TCGPlayerCredentials

logger = logging.getLogger(__name__)

class BaseTCGPlayerService(BaseExternalService):
    STORE_BASE_URL = "https://store.tcgplayer.com"
    LOGIN_ENDPOINT = "/oauth/login"
    PRICING_ENDPOINT = "/Admin/Pricing"

    def __init__(self):
        super().__init__(base_url=self.STORE_BASE_URL)
        
        # Set up endpoints
        self.login_endpoint = self.LOGIN_ENDPOINT
        self.pricing_endpoint = self.PRICING_ENDPOINT
        self.staged_inventory_endpoint = f"{self.PRICING_ENDPOINT}/DownloadStagedInventoryExportCSV?type=Pricing"
        self.live_inventory_endpoint = f"{self.PRICING_ENDPOINT}/DownloadMyExportCSV?type=Pricing"
        self.pricing_export_endpoint = f"{self.PRICING_ENDPOINT}/downloadexportcsv"
        
        self.credentials = TCGPlayerCredentials()

    def _get_headers(self, method: str, content_type: str = 'application/x-www-form-urlencoded') -> Dict[str, str]:
        """Get headers based on the HTTP method and content type
        
        Args:
            method: HTTP method (GET, POST, etc.)
            content_type: Content type for the request. Defaults to 'application/x-www-form-urlencoded'
        """
        base_headers = {
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
            'accept-language': 'en-US,en;q=0.8',
            'priority': 'u=0, i',
            'referer': 'https://sellerportal.tcgplayer.com/',
            'origin': 'https://sellerportal.tcgplayer.com',
            'sec-ch-ua': '"Not A(Brand";v="8", "Chromium";v="132", "Brave";v="132"',
            'sec-ch-ua-mobile': '?0', 
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'document',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-user': '?1',
            'sec-gpc': '1',
            'upgrade-insecure-requests': '1',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36'
        }
        
        if method == 'POST':
            post_headers = {
                'cache-control': 'max-age=0',
                'content-type': content_type
            }
            base_headers.update(post_headers)
            
        return base_headers

    async def _make_request(
        self,
        method: str,
        endpoint: str,
        params: Optional[Dict[str, Any]] = None,
        headers: Optional[Dict[str, str]] = None,
        data: Optional[Dict[str, Any]] = None,
        auth_required: bool = True,
        download_file: bool = False
    ) -> Union[Dict[str, Any], bytes]:
        # Get the authentication cookie if required
        if auth_required:
            cookie = self.credentials.get_cookie()
            if not cookie:
                raise RuntimeError("TCGPlayer authentication cookie not set. Please set the cookie using TCGPlayerCredentials.set_cookie()")
            
            # Get method-specific headers and update with any provided headers
            request_headers = self._get_headers(method)
            if headers:
                request_headers.update(headers)
            request_headers["Cookie"] = cookie
        else:
            request_headers = headers or {}

        try:
            # Use the parent class's _make_request with our custom headers and binary flag
            response = await super()._make_request(
                method=method,
                endpoint=endpoint,
                params=params,
                headers=request_headers,
                data=data,
                binary=download_file
            )

            if isinstance(response, dict) and response.get('status') == 401:
                raise RuntimeError("TCGPlayer authentication failed. Cookie may be invalid or expired.")

            return response

        except aiohttp.ClientError as e:
            logger.error(f"TCGPlayer API request failed: {str(e)}")
            raise
        except Exception as e:
            logger.error(f"Unexpected error during TCGPlayer API request: {str(e)}")
            raise