"""``haute train`` command."""

from pathlib import Path

import click


@click.command()
@click.argument("training_script")
def train(training_script: str) -> None:
    """Run a model training job from a training script.

    The script should define a ``TrainingJob`` instance named ``job``
    with a ``.run()`` method (as generated by ``haute export``).

    \b
    Examples:
      haute train training/frequency.py
      haute train train_severity.py
    """
    import importlib.util

    filepath = Path(training_script)
    if not filepath.exists():
        click.echo(f"Error: Training script not found: {filepath}", err=True)
        raise SystemExit(1)

    click.echo(f"Running training script: {filepath}")

    # Validate the script for dangerous patterns before execution
    from haute._sandbox import UnsafeCodeError, validate_user_code

    try:
        validate_user_code(filepath.read_text(), allow_imports=True)
    except UnsafeCodeError as e:
        click.echo(f"Error: Training script failed safety validation: {e}", err=True)
        raise SystemExit(1)

    # Load the script as a module
    spec = importlib.util.spec_from_file_location("training_script", filepath)
    if spec is None or spec.loader is None:
        click.echo(f"Error: Cannot load {filepath}", err=True)
        raise SystemExit(1)
    mod = importlib.util.module_from_spec(spec)
    try:
        spec.loader.exec_module(mod)
    except Exception as e:
        click.echo(f"Error executing script: {e}", err=True)
        raise SystemExit(1)

    # Find the TrainingJob instance
    job = getattr(mod, "job", None)
    if job is None:
        click.echo("Error: No 'job' variable found in training script.", err=True)
        click.echo("  The script should define: job = TrainingJob(...)", err=True)
        raise SystemExit(1)

    try:
        def _progress(msg: str, frac: float) -> None:
            bar = "=" * int(frac * 30)
            click.echo(f"\r  [{bar:<30}] {frac:.0%} {msg}", nl=False)

        result = job.run(progress=_progress)
        click.echo()  # newline after progress bar
        click.echo(f"\n  \u2713 Model saved to: {result.model_path}")
        click.echo(f"  \u2713 Train: {result.train_rows:,} rows, Test: {result.test_rows:,} rows")
        n_cat = len(result.cat_features)
        click.echo(f"  \u2713 Features: {len(result.features)} ({n_cat} categorical)")
        click.echo("\n  Metrics:")
        for name, value in result.metrics.items():
            click.echo(f"    {name}: {value:.4f}")
    except Exception as e:
        click.echo(f"\n  \u2717 Training failed: {e}", err=True)
        raise SystemExit(1)
