"""File type detection for YAML files."""

from __future__ import annotations

from pathlib import Path

from ..models import FileType


def detect_file_type(content: str, file_path: str = "") -> FileType:
    """Detect the type of YAML file from content and path."""
    path_lower = file_path.lower()
    fname = Path(file_path).name.lower() if file_path else ""

    # GitHub Actions
    if ".github/workflows" in path_lower or ".github\\workflows" in path_lower:
        return FileType.GITHUB_ACTIONS
    if fname.endswith((".yml", ".yaml")) and "on:" in content and "jobs:" in content:
        if "runs-on:" in content or "uses:" in content:
            return FileType.GITHUB_ACTIONS

    # GitLab CI
    if fname == ".gitlab-ci.yml" or fname == ".gitlab-ci.yaml":
        return FileType.GITLAB_CI
    if "stages:" in content and ("script:" in content or "image:" in content):
        if "stage:" in content:
            return FileType.GITLAB_CI

    # Docker Compose
    if fname in ("docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml"):
        return FileType.DOCKER_COMPOSE
    if "services:" in content and ("image:" in content or "build:" in content):
        if "version:" in content or "networks:" in content or "volumes:" in content:
            return FileType.DOCKER_COMPOSE

    # Helm
    if fname == "chart.yaml" or fname == "chart.yml":
        return FileType.HELM
    if "apiVersion:" in content and ("appVersion:" in content or "dependencies:" in content):
        if "name:" in content and "version:" in content:
            return FileType.HELM
    if fname.startswith("values") and fname.endswith((".yml", ".yaml")):
        return FileType.HELM

    # Kubernetes
    if "apiVersion:" in content and "kind:" in content:
        return FileType.KUBERNETES

    # Generic YAML
    if fname.endswith((".yml", ".yaml")):
        return FileType.GENERIC_YAML

    return FileType.UNKNOWN
