import sys
import click
from .config import load_config, load_environment
from .checks.docker import check_docker
from .checks.env import check_env
from .checks.ports import check_ports
from .checks.k8s import check_k8s
from .checks.files import check_files

# Constants for status symbols
SUCCESS = "✔"
FAILURE = "❌"
WARNING = "⚠"

@click.group()
def main():
    """🩺 Pre-Deploy Doctor: A local DevOps readiness checker."""
    pass

@main.command()
def check():
    """Run all readiness checks."""
    click.echo("\n🩺 Pre-Deploy Doctor Report\n")
    
    config = load_config()
    load_environment()
    
    overall_safe = True
    
    # 1. Docker Check
    docker_success, docker_msg = check_docker()
    if docker_success:
        click.secho(f"{SUCCESS} {docker_msg}", fg="green")
    else:
        click.secho(f"{FAILURE} {docker_msg}", fg="red")
        overall_safe = False

    # 2. File Checks
    file_results = check_files()
    for success, msg in file_results:
        if success:
            click.secho(f"{SUCCESS} {msg}", fg="green")
        else:
            click.secho(f"{FAILURE} {msg}", fg="red")
            overall_safe = False

    # 3. Env Checks
    env_results = check_env(config)
    for success, msg in env_results:
        if success:
            click.secho(f"{SUCCESS} {msg}", fg="green")
        else:
            click.secho(f"{FAILURE} {msg}", fg="red")
            overall_safe = False

    # 4. Port Checks
    port_results = check_ports(config)
    for success, msg in port_results:
        if success:
            click.secho(f"{SUCCESS} {msg}", fg="green")
        else:
            click.secho(f"{FAILURE} {msg}", fg="red")
            overall_safe = False

    # 5. K8s Checks (Warnings)
    k8s_results = check_k8s(config)
    for success, msg, level in k8s_results:
        if level == "success":
            click.secho(f"{SUCCESS} {msg}", fg="green")
        elif level == "warning":
            click.secho(f"{WARNING} {msg}", fg="yellow")
        else:
            click.secho(f"{FAILURE} {msg}", fg="red")
            overall_safe = False

    click.echo("\n" + "="*30)
    if overall_safe:
        click.secho(f"Status: {SUCCESS} SAFE TO DEPLOY", bold=True, fg="green")
        sys.exit(0)
    else:
        click.secho(f"Status: {FAILURE} NOT SAFE TO DEPLOY", bold=True, fg="red")
        sys.exit(1)

if __name__ == "__main__":
    main()
