"""Store the engine's suggestion for every imported forecast under the active config.

    python -m cli.backfill --center sac
"""

import typer

from app.calibration import agreement, backfill
from app.engine import ENGINE_VERSION

from .common import center_by_slug, connect

app = typer.Typer()


@app.command()
def main(center: str = typer.Option(...)):
    with connect() as conn:
        c = center_by_slug(conn, center)
        cfg = conn.execute("SELECT * FROM center_configs WHERE center_id = %s AND status = 'active'", (c["id"],)).fetchone()
        if not cfg:
            raise SystemExit("Center has no active config")
        n = backfill(conn, c["id"], cfg)
        stats = agreement(conn, c["id"], cfg["config"])["overall"]
    typer.echo(f"backfilled {n} forecasts with config v{cfg['version']} / engine {ENGINE_VERSION}")
    typer.echo(f"agreement: n={stats['n']} exact={stats['exact']} within_one={stats['within_one']} bias={stats['bias']} kappa={stats['kappa']}")


if __name__ == "__main__":
    app()
