import os
import subprocess
from datetime import datetime
from pathlib import Path


def _format_code(code: str):
    try:
        return subprocess.run(
            [
                "ruff",
                "format",
                "--config",
                Path(__file__).parent.parent / "ruff.toml",
                "-",
            ],
            check=True,
            input=code,
            encoding="utf-8",
            capture_output=True,
        ).stdout
    except subprocess.CalledProcessError as e:
        raise Exception(f"Error while formatting code:\n{code}\n{e.stderr}")


def _generate_flow_name() -> str:
    return f"sdk_generated_flow_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}"


def _generate_test_case_name() -> str:
    return f"sdk_generated_test_case_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}"


def _check_create_dir(dir_path: str):
    if not os.path.exists(dir_path):
        os.mkdir(dir_path)


def _create_init_file(path: str):
    init_file_path = Path(path) / "__init__.py"
    if not init_file_path.exists():
        with open(init_file_path, "w") as f:
            f.write("# This is an empty __init__.py file to make this directory a package.\n")


def _autogenerated_header() -> str:
    """
    Returns a descriptive comment for the top of the autogenerated files
    """
    return "# This code was autogenerated by PythonGenerator\n"
