from __future__ import annotations

import argparse
import json
import logging
import shutil
import sys
from pathlib import Path

from sfi.projectparse.projectparse import parse_project_data

logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger(__name__)
cwd = Path.cwd()


def _get_build_command_from_toml(directory: Path) -> str | None:
    """Get build command from pyproject.toml."""
    logger.debug(f"Parsing pyproject.toml in {directory}")

    project_name = directory.stem
    project_data = parse_project_data(directory=directory, recursive=False).get(project_name, None)
    if not project_data:
        logger.error(f"No project data found in {directory}")
        return None

    if "build_backend" in project_data:
        build_backend = project_data["build_backend"]
        if build_backend.startswith("poetry."):
            return "poetry"
        elif build_backend.startswith("hatchling."):
            return "hatchling"
        else:
            logger.error(f"Unknown build-backend: {build_backend}")
            return None

    logger.error("No `build_backend` found in project data: ")
    logger.error(json.dumps(project_data, indent=2, ensure_ascii=False, sort_keys=True))
    return None


def _get_build_command(directory: Path):
    """Get build command from directory."""
    project_path = directory / "pyproject.toml"
    if project_path.is_file():
        logger.debug(f"Found pyproject.toml in {directory}")
        return _get_build_command_from_toml(directory)

    commands = ["uv", "poetry", "hatchling"]
    for command in commands:
        if shutil.which(command):
            logger.debug(f"Found build command: {command}")
            return command
    logger.error(f"No build command found in {directory}")
    sys.exit(1)
    return None


def main():
    parser = argparse.ArgumentParser(description="Make Python")
    parser.add_argument("--debug", "-d", action="store_true", help="Enable debug mode")

    args = parser.parse_args()
    if args.debug:
        logger.setLevel(logging.DEBUG)

    build_command = _get_build_command(cwd)
    logger.info(f"Build command: {build_command}")
