import subprocess
import sys
import os
import shutil

# DOCKER_DIR = "docker"


def check_docker_installed():
    try:
        subprocess.run(
            ["docker", "--version"],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
    except subprocess.CalledProcessError:
        print("Docker is not installed. Please install Docker and try again.")
        sys.exit(1)


def check_docker_running():
    try:
        subprocess.run(
            ["docker", "info"],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
    except subprocess.CalledProcessError:
        print("Docker is not running. Please start Docker and try again.")
        sys.exit(1)


def run_docker_compose():
    try:
        # os.chdir(DOCKER_DIR)
        subprocess.run(["docker-compose", "up", "-d"], check=True)
        print("Docker Compose started.")
    except subprocess.CalledProcessError as e:
        print(f"Failed to start Docker Compose: {e}")
        sys.exit(1)
    finally:
        os.chdir("..")


def run_uvicorn():
    try:
        subprocess.run(["python", "runserver.py"], check=True)
    except subprocess.CalledProcessError as e:
        print(f"Failed to start Uvicorn: {e}")
        sys.exit(1)


def check_python_version():
    try:
        result = subprocess.run(
            ["python3.12", "--version"],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        version = result.stdout.decode().strip()
        if "Python 3.12" not in version:
            raise subprocess.CalledProcessError(1, "python3.12", "Incorrect version")
    except subprocess.CalledProcessError:
        print("Python 3.12 is not installed. Please install Python 3.12 and try again.")
        sys.exit(1)


def main():
    print("Please read the README.md file before proceeding.")
    print("Press 'Enter' to confirm or any other key to exit.")

    confirmation = input().strip()
    if confirmation != "":
        sys.exit(0)

    print("Choose an option to run the application:")
    print("1. Docker")
    print("2. Local")

    choice = input("Enter your choice (1 or 2): ").strip()

    if choice == "1":
        check_docker_installed()
        check_docker_running()
        shutil.copy("config/docker.env", ".env")
        shutil.copy("config/docker_config.py", "src/core/config.py")
        print("Environment set up for Docker.")
        run_docker_compose()
    elif choice == "2":
        check_python_version()
        print("Running application directly without Docker...")
        shutil.copy("config/local.env", ".env")
        shutil.copy("config/local_config.py", "src/core/config.py")
        print("Environment set up for local development.")
        run_uvicorn()
    else:
        print("Invalid choice. Please enter '1' or '2'.")
        sys.exit(1)


if __name__ == "__main__":
    main()
