import click
import uvicorn

from chandanops.core.project_generator import ProjectGenerator
from chandanops.core.registry_manager import RegistryManager
from chandanops.core.mlflow_manager import MLflowManager
from chandanops.serving.app_factory import create_app


@click.group()
def main():
    """ChandanOps CLI"""
    pass


@main.command()
@click.argument("name")
def init(name):
    generator = ProjectGenerator()
    generator.create_project(name)
    click.echo(f"Project '{name}' created.")


@main.command()
@click.option("--model", default="artifacts/model.pkl")
def serve(model):
    app = create_app(model_path=model)
    uvicorn.run(app, host="0.0.0.0", port=8000)


@main.command()
@click.option("--model-name", required=True)
@click.option("--version", required=True, type=int)
@click.option("--stage", required=True)
def promote(model_name, version, stage):
    registry = RegistryManager()
    registry.promote(model_name, version, stage)
    click.echo(f"{model_name} v{version} promoted to {stage}")


@main.command()
@click.option("--metric", required=True)
@click.option("--top", default=5)
def compare(metric, top):
    manager = MLflowManager()
    df = manager.compare_runs(metric, top)
    if df is None:
        click.echo("No runs found.")
    else:
        click.echo(df.to_string(index=False))
