"""Docker service detection utilities."""

from __future__ import annotations

import logging
import re

logger = logging.getLogger(__name__)

# Patterns for files that could affect docker builds
DOCKER_RELATED_PATTERNS = [
    r".*Dockerfile.*",
    r".*docker-compose.*\.yaml",
    r".*docker-compose.*\.yml",
    r".*\.dockerignore",
    r".*pyproject\.toml",
    r".*uv\.lock",
    r".*requirements.*\.txt",
    r".*Pipfile",
    r".*poetry\.lock",
    r".*package\.json",
    r".*package-lock\.json",
    r".*yarn\.lock",
    r".*build\.gradle\.kts",
    r".*settings\.gradle\.kts",
    r".*gradle\.properties",
    r".*gradle-wrapper\.properties",
    r".*pom\.xml",
    r".*Makefile",
]


def detect_docker_related_changes(changed_files: list[str] | None) -> tuple[bool, list[str]]:
    """
    Detect if any changed files could affect docker builds.

    Args:
        changed_files: List of changed file paths (relative to workspace root)

    Returns:
        Tuple of (should_trigger_build, matching_files)
    """
    if not changed_files:
        return False, []

    matching_files: list[str] = []
    for file_path in changed_files:
        for pattern in DOCKER_RELATED_PATTERNS:
            if re.search(pattern, file_path, re.IGNORECASE):
                matching_files.append(file_path)
                logger.info(f"Detected docker-related change: {file_path} (matched pattern: {pattern})")
                break

    return len(matching_files) > 0, matching_files


def detect_service_from_path(file_path: str) -> str | None:
    """
    Detect which service a changed file belongs to.

    Args:
        file_path: Path to changed file (relative to workspace root)

    Returns:
        Service directory path or None if not a service file
    """
    # Common service directory patterns
    service_patterns = [
        r"^microservices/([^/]+)/",
        r"^components/([^/]+)/",
        r"^k8s/([^/]+)/",
        r"^tools/([^/]+)/",
    ]

    for pattern in service_patterns:
        match = re.search(pattern, file_path)
        if match:
            service_name = match.group(1)
            # Return the full path to the service directory
            if file_path.startswith("microservices/"):
                return f"microservices/{service_name}"
            elif file_path.startswith("components/"):
                return f"components/{service_name}"
            elif file_path.startswith("k8s/"):
                return f"k8s/{service_name}"
            elif file_path.startswith("tools/"):
                return f"tools/{service_name}"

    return None


def get_build_contexts_for_service(service_dir: str) -> list[str]:
    """
    Get build contexts for a specific service (matching pipeline behavior).

    Args:
        service_dir: Service directory path (e.g., "microservices/tabular-exporter")

    Returns:
        List of build context strings (e.g., ["proto=proto-files"])
    """
    build_contexts: list[str] = []

    # tabular-exporter needs proto-files context
    if "tabular-exporter" in service_dir:
        build_contexts.append("proto=proto-files")

    # Add more service-specific contexts as needed
    # if "gen-ai" in service_dir:
    #     build_contexts.append("some-context=some-path")

    return build_contexts


def get_secrets_for_service(service_dir: str) -> list[str]:
    """
    Get secrets needed for a specific service build.

    Args:
        service_dir: Service directory path

    Returns:
        List of secret specifications (e.g., ["id=GH_TOKEN,env=GH_TOKEN"])
    """
    secrets: list[str] = []

    # tabular-exporter needs GH_TOKEN for formatter wheels
    if "tabular-exporter" in service_dir:
        secrets.append("id=GH_TOKEN,env=GH_TOKEN")

    # Add more service-specific secrets as needed

    return secrets
