"""Template and config rendering helpers used by CLI commands."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from cihub.config.io import load_yaml_file
from cihub.utils.paths import hub_root


def detect_java_build_tool(repo_path: Path | None) -> str:
    """Detect Java build tool from repo structure.

    Returns 'gradle' if build.gradle exists, otherwise 'maven'.
    """
    if repo_path is None:
        return "maven"
    repo_path = Path(repo_path)
    if (repo_path / "build.gradle").exists() or (repo_path / "build.gradle.kts").exists():
        return "gradle"
    if (repo_path / "settings.gradle").exists() or (repo_path / "settings.gradle.kts").exists():
        return "gradle"
    return "maven"


def build_repo_config(
    language: str,
    owner: str,
    name: str,
    branch: str,
    subdir: str | None = None,
    repo_path: Path | None = None,
    install_from: str = "pypi",
) -> dict[str, Any]:
    template_path = hub_root() / "templates" / "repo" / ".ci-hub.yml"
    base = load_yaml_file(template_path)

    repo_block = base.get("repo", {}) if isinstance(base.get("repo"), dict) else {}
    repo_block["owner"] = owner
    repo_block["name"] = name
    repo_block["language"] = language
    repo_block["default_branch"] = branch
    repo_block.setdefault("dispatch_workflow", "hub-ci.yml")
    if subdir:
        repo_block["subdir"] = subdir
    base["repo"] = repo_block

    base["language"] = language

    if language == "java":
        base.pop("python", None)
        # Detect build tool from repo structure
        java_block = base.get("java", {})
        if isinstance(java_block, dict):
            java_block["build_tool"] = detect_java_build_tool(repo_path)
            base["java"] = java_block
    elif language == "python":
        base.pop("java", None)

    base.setdefault("version", "1.0")

    # Add install configuration for CI bootstrap
    if install_from:
        base["install"] = {"source": install_from}

    return base


def render_caller_workflow(language: str) -> str:
    templates_dir = hub_root() / "templates" / "repo"
    if language == "java":
        template_path = templates_dir / "hub-java-ci.yml"
        replacement = "hub-java-ci.yml"
    else:
        template_path = templates_dir / "hub-python-ci.yml"
        replacement = "hub-python-ci.yml"

    content = template_path.read_text(encoding="utf-8")
    content = content.replace(replacement, "hub-ci.yml")
    header = "# Generated by cihub init - DO NOT EDIT\n"
    return header + content


def render_dispatch_workflow(language: str, dispatch_workflow: str) -> str:
    templates_dir = hub_root() / "templates" / "repo"
    if dispatch_workflow == "hub-ci.yml":
        if not language:
            raise ValueError("language is required for hub-ci.yml rendering")
        return render_caller_workflow(language)
    if dispatch_workflow == "hub-java-ci.yml":
        return (templates_dir / "hub-java-ci.yml").read_text(encoding="utf-8")
    if dispatch_workflow == "hub-python-ci.yml":
        return (templates_dir / "hub-python-ci.yml").read_text(encoding="utf-8")
    raise ValueError(f"Unsupported dispatch_workflow: {dispatch_workflow}")
