# cli/biometric_cli.py
import click
from datetime import date, timedelta
from flask.cli import with_appcontext

from routes.biometric import sync_biometric_for_date


@click.command("daily-biometrics")
@click.option(
    "--date",
    "target_date",
    type=click.DateTime(formats=["%Y-%m-%d"]),
    required=False,
    help="Date to sync in YYYY-MM-DD (default = yesterday)",
)
@with_appcontext
def daily_biometrics(target_date=None):
    """
    Run ONLY biometric sync for a single date.
    Used by cron jobs to fetch yesterday's biometric punches automatically.
    """

    # Determine the target date
    if target_date:
        target_date = target_date.date()
    else:
        target_date = date.today() - timedelta(days=1)

    click.echo(f"▶ Running biometric sync for {target_date}")

    try:
        run = sync_biometric_for_date(target_date, source_name="default")
        click.echo(f"  ✓ Biometric sync result: {run.status} — {run.message}")
    except Exception as e:  # noqa: BLE001
        click.echo(f"  ❌ Failed biometric sync: {e}")