from __future__ import annotations

import argparse
from datetime import date

from backend.application import SERVICE
from backend.bootstrap.config import normalize_date


def main() -> None:
    parser = argparse.ArgumentParser(description="Sync Xiaobai Review data to SQLite")
    parser.add_argument("--account", required=True, help="Account name whose Tushare Token is used")
    parser.add_argument("--date", default=date.today().isoformat(), help="Trade date: YYYY-MM-DD")
    args = parser.parse_args()

    user = SERVICE.database.user_by_username(args.account.strip())
    if not user:
        raise SystemExit("account not found")
    SERVICE.bind_user(int(user["id"]))
    trade_date = normalize_date(args.date)
    dashboard = SERVICE.sync_dashboard(trade_date)
    counts = {
        key: len(dashboard.get(key) or [])
        for key in ("limits", "broken", "down_limits", "yesterday_limits")
    }
    print(
        f"sync complete: date={dashboard['meta']['trade_date']} "
        f"source={dashboard['meta']['source']} counts={counts}"
    )


if __name__ == "__main__":
    main()
