"""Utility functions related to environment checking."""

import logging
import os

from .urls import is_atlassian_cloud_url

logger = logging.getLogger("mcp-atlassian.utils.environment")


def get_available_services(
    headers: dict[str, str] | None = None,
) -> dict[str, bool | None]:
    """Determine which services are available based on environment variables and optional headers."""
    headers = headers or {}
    confluence_url = os.getenv("CONFLUENCE_URL")
    confluence_is_setup = False
    if confluence_url:
        is_cloud = is_atlassian_cloud_url(confluence_url)

        # Cloud OAuth check (needs cloud_id)
        if all(
            [
                os.getenv("ATLASSIAN_OAUTH_CLIENT_ID")
                or os.getenv("CONFLUENCE_OAUTH_CLIENT_ID"),
                os.getenv("ATLASSIAN_OAUTH_CLIENT_SECRET")
                or os.getenv("CONFLUENCE_OAUTH_CLIENT_SECRET"),
                os.getenv("ATLASSIAN_OAUTH_CLOUD_ID"),
            ]
        ):
            confluence_is_setup = True
            logger.info("Using Confluence OAuth 2.0 (3LO) authentication (Cloud)")
        # DC OAuth check (no cloud_id, but has client credentials + non-cloud URL)
        elif (
            not is_cloud
            and (
                os.getenv("ATLASSIAN_OAUTH_CLIENT_ID")
                or os.getenv("CONFLUENCE_OAUTH_CLIENT_ID")
            )
            and (
                os.getenv("ATLASSIAN_OAUTH_CLIENT_SECRET")
                or os.getenv("CONFLUENCE_OAUTH_CLIENT_SECRET")
            )
        ):
            confluence_is_setup = True
            logger.info("Using Confluence OAuth 2.0 authentication (Data Center)")
        elif all(
            [
                os.getenv("ATLASSIAN_OAUTH_ACCESS_TOKEN")
                or os.getenv("CONFLUENCE_OAUTH_ACCESS_TOKEN"),
                os.getenv("ATLASSIAN_OAUTH_CLOUD_ID"),
            ]
        ):
            confluence_is_setup = True
            logger.info(
                "Using Confluence OAuth 2.0 (3LO) authentication (Cloud) "
                "with provided access token"
            )
        # DC BYO access token (no cloud_id, non-cloud URL)
        elif not is_cloud and (
            os.getenv("ATLASSIAN_OAUTH_ACCESS_TOKEN")
            or os.getenv("CONFLUENCE_OAUTH_ACCESS_TOKEN")
        ):
            confluence_is_setup = True
            logger.info(
                "Using Confluence OAuth 2.0 authentication (Data Center) "
                "with provided access token"
            )
        elif is_cloud:  # Cloud non-OAuth
            if all(
                [
                    os.getenv("CONFLUENCE_USERNAME"),
                    os.getenv("CONFLUENCE_API_TOKEN"),
                ]
            ):
                confluence_is_setup = True
                logger.info("Using Confluence Cloud Basic Authentication (API Token)")
        else:  # Server/Data Center non-OAuth
            if os.getenv("CONFLUENCE_PERSONAL_TOKEN") or (
                os.getenv("CONFLUENCE_USERNAME") and os.getenv("CONFLUENCE_API_TOKEN")
            ):
                confluence_is_setup = True
                logger.info(
                    "Using Confluence Server/Data Center authentication (PAT or Basic Auth)"
                )

    if not confluence_is_setup and os.getenv("ATLASSIAN_OAUTH_ENABLE", "").lower() in (
        "true",
        "1",
        "yes",
    ):
        confluence_is_setup = True
        logger.info(
            "Using Confluence minimal OAuth configuration "
            "- expecting user-provided tokens via headers"
        )

    if not confluence_is_setup:
        confluence_token = headers.get("X-Atlassian-Confluence-Personal-Token")
        confluence_url_header = headers.get("X-Atlassian-Confluence-Url")

        if confluence_token and confluence_url_header:
            confluence_is_setup = True
            logger.info("Using Confluence authentication from header personal token")

    jira_url = os.getenv("JIRA_URL")
    jira_is_setup = False
    if jira_url:
        is_cloud = is_atlassian_cloud_url(jira_url)
        # Cloud OAuth check (needs cloud_id)
        if all(
            [
                os.getenv("ATLASSIAN_OAUTH_CLIENT_ID")
                or os.getenv("JIRA_OAUTH_CLIENT_ID"),
                os.getenv("ATLASSIAN_OAUTH_CLIENT_SECRET")
                or os.getenv("JIRA_OAUTH_CLIENT_SECRET"),
                os.getenv("ATLASSIAN_OAUTH_CLOUD_ID"),
            ]
        ):
            jira_is_setup = True
            logger.info("Using Jira OAuth 2.0 (3LO) authentication (Cloud)")
        # DC OAuth check (no cloud_id, but has client credentials + non-cloud URL)
        elif (
            not is_cloud
            and (
                os.getenv("ATLASSIAN_OAUTH_CLIENT_ID")
                or os.getenv("JIRA_OAUTH_CLIENT_ID")
            )
            and (
                os.getenv("ATLASSIAN_OAUTH_CLIENT_SECRET")
                or os.getenv("JIRA_OAUTH_CLIENT_SECRET")
            )
        ):
            jira_is_setup = True
            logger.info("Using Jira OAuth 2.0 authentication (Data Center)")
        elif all(
            [
                os.getenv("ATLASSIAN_OAUTH_ACCESS_TOKEN")
                or os.getenv("JIRA_OAUTH_ACCESS_TOKEN"),
                os.getenv("ATLASSIAN_OAUTH_CLOUD_ID"),
            ]
        ):
            jira_is_setup = True
            logger.info(
                "Using Jira OAuth 2.0 (3LO) authentication (Cloud) "
                "with provided access token"
            )
        # DC BYO access token (no cloud_id, non-cloud URL)
        elif not is_cloud and (
            os.getenv("ATLASSIAN_OAUTH_ACCESS_TOKEN")
            or os.getenv("JIRA_OAUTH_ACCESS_TOKEN")
        ):
            jira_is_setup = True
            logger.info(
                "Using Jira OAuth 2.0 authentication (Data Center) "
                "with provided access token"
            )
        elif is_cloud:  # Cloud non-OAuth
            if all(
                [
                    os.getenv("JIRA_USERNAME"),
                    os.getenv("JIRA_API_TOKEN"),
                ]
            ):
                jira_is_setup = True
                logger.info("Using Jira Cloud Basic Authentication (API Token)")
        else:  # Server/Data Center non-OAuth
            if os.getenv("JIRA_PERSONAL_TOKEN") or (
                os.getenv("JIRA_USERNAME") and os.getenv("JIRA_API_TOKEN")
            ):
                jira_is_setup = True
                logger.info(
                    "Using Jira Server/Data Center authentication (PAT or Basic Auth)"
                )

    if not jira_is_setup and os.getenv("ATLASSIAN_OAUTH_ENABLE", "").lower() in (
        "true",
        "1",
        "yes",
    ):
        jira_is_setup = True
        logger.info(
            "Using Jira minimal OAuth configuration "
            "- expecting user-provided tokens via headers"
        )

    if not jira_is_setup:
        jira_token = headers.get("X-Atlassian-Jira-Personal-Token")
        jira_url_header = headers.get("X-Atlassian-Jira-Url")

        if jira_token and jira_url_header:
            jira_is_setup = True
            logger.info("Using Jira authentication from header personal token")

    if not confluence_is_setup:
        logger.info(
            "Confluence is not configured or required environment variables are missing."
        )
    if not jira_is_setup:
        logger.info(
            "Jira is not configured or required environment variables are missing."
        )

    return {"confluence": confluence_is_setup, "jira": jira_is_setup}
