"""Factory for creating platform-specific handler pairs."""

from __future__ import annotations

from code_reviewer.adaptors.issue import GitHubIssueHandler, GitLabIssueHandler, IssueHandler
from code_reviewer.adaptors.repository import (
    GitHubRepositoryHandler,
    GitLabRepositoryHandler,
    RepositoryHandler,
)
from code_reviewer.config import Config
from code_reviewer.logging_config import BaseLogger

logger = BaseLogger("adaptors", "factory")


def create_platform_handlers(
    platform: str, config: Config
) -> tuple[RepositoryHandler, IssueHandler]:
    """Create repository and issue handlers for the given platform.

    Args:
        platform: "github" or "gitlab"
        config: Application config with API URLs and tokens.

    Returns:
        (RepositoryHandler, IssueHandler) tuple.

    Raises:
        NotImplementedError: If the platform is not supported.
    """
    repository: RepositoryHandler
    issue_handler: IssueHandler

    if platform == "github":
        if config.github_api_token:
            logger.debug(f"Creating GitHub handlers for {config.github_api_url}")
            repository = GitHubRepositoryHandler.from_token(
                api_url=config.github_api_url, token=config.github_api_token
            )
            issue_handler = GitHubIssueHandler.from_token(
                api_url=config.github_api_url, token=config.github_api_token
            )
        else:
            logger.info("No GitHub token found, using gh CLI for authentication")
            repository = GitHubRepositoryHandler.from_cli(api_url=config.github_api_url)
            issue_handler = GitHubIssueHandler.from_cli(api_url=config.github_api_url)
    elif platform == "gitlab":
        if config.gitlab_api_token:
            logger.debug(f"Creating GitLab handlers for {config.gitlab_api_url}")
            repository = GitLabRepositoryHandler.from_token(
                api_url=config.gitlab_api_url, token=config.gitlab_api_token
            )
            issue_handler = GitLabIssueHandler.from_token(
                api_url=config.gitlab_api_url, token=config.gitlab_api_token
            )
        else:
            logger.info("No GitLab token found, using glab CLI for authentication")
            repository = GitLabRepositoryHandler.from_cli(api_url=config.gitlab_api_url)
            issue_handler = GitLabIssueHandler.from_cli(api_url=config.gitlab_api_url)
    else:
        raise NotImplementedError(f"Unsupported platform: {platform}")

    return repository, issue_handler
