"""Main synchronous client for sed.sh API."""

from typing import Optional
import requests
from sed_sh.config import Config
from sed_sh.services.links import LinksService
from sed_sh.services.malware import MalwareService
from sed_sh.services.inbox import InboxService
from sed_sh.services.routes import RoutesService
from sed_sh.services.reports import ReportsService


class SedSH:
    """Main synchronous client for sed.sh API.

    This client provides access to all sed.sh services through a unified interface.

    Authentication:
        API key can be provided in three ways (in order of priority):
        1. Directly in constructor: SedSH(api_key="your-key")
        2. Environment variable: SEDSH_API_KEY
        3. Config file: ~/.sedsh/config.json

    Example:
        >>> from sed_sh import SedSH
        >>>
        >>> # Initialize client
        >>> client = SedSH(api_key="your-api-key")
        >>>
        >>> # Use services
        >>> link = client.links.create("https://example.com")
        >>> inbox = client.inbox.create()
        >>> scan = client.malware.scan_file("/path/to/file.pdf")
        >>>
        >>> # Context manager support
        >>> with SedSH(api_key="your-key") as client:
        ...     link = client.links.create("https://example.com")

    Attributes:
        links: Links/URL shortener service
        malware: Malware scanning service
        inbox: Disposable email inbox service
        routes: Mock API/Routes service
        reports: PDF reports service
    """

    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: Optional[str] = None,
        timeout: Optional[int] = None,
    ):
        """Initialize the sed.sh client.

        Args:
            api_key: API key (optional if set via env var or config file)
            base_url: API base URL (default: https://api.sed.sh)
            timeout: Request timeout in seconds (default: 30)

        Raises:
            ValueError: If API key cannot be found
        """
        # Load configuration
        config = Config.load(api_key=api_key, base_url=base_url, timeout=timeout)

        self.api_key = config["api_key"]
        self.base_url = config["base_url"]
        self.timeout = config["timeout"]

        if not self.api_key:
            raise ValueError(
                "API key not found. Provide it via:\n"
                "1. Constructor: SedSH(api_key='your-key')\n"
                "2. Environment: export SEDSH_API_KEY='your-key'\n"
                "3. Config file: ~/.sedsh/config.json"
            )

        # Initialize services (each service creates its own session)
        self.links = LinksService(
            base_url=self.base_url,
            api_key=self.api_key,
            timeout=self.timeout,
        )
        self.malware = MalwareService(
            base_url=self.base_url,
            api_key=self.api_key,
            timeout=self.timeout,
        )
        self.inbox = InboxService(
            base_url=self.base_url,
            api_key=self.api_key,
            timeout=self.timeout,
        )
        self.routes = RoutesService(
            base_url=self.base_url,
            api_key=self.api_key,
            timeout=self.timeout,
        )
        self.reports = ReportsService(
            base_url=self.base_url,
            api_key=self.api_key,
            timeout=self.timeout,
        )

    def __enter__(self):
        """Context manager entry."""
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """Context manager exit."""
        self.close()

    def close(self):
        """Close all service sessions."""
        # Close all service sessions
        for service in [self.links, self.malware, self.inbox, self.routes, self.reports]:
            if hasattr(service, 'close'):
                service.close()
