from __future__ import annotations from datetime import date from flask import Blueprint, jsonify, request from app.services.historical_sync import get_historical_sync_service from app.utils.serialization import to_plain historical_blueprint = Blueprint("historical", __name__) service = get_historical_sync_service() @historical_blueprint.get("/historical/status") def historical_status(): return jsonify(to_plain(service.status())) @historical_blueprint.post("/historical/start") def historical_start(): payload = request.get_json(silent=True) or {} try: status = service.start( start_date=_parse_date(payload.get("start_date")), end_date=_parse_date(payload.get("end_date")), chunk_days=payload.get("chunk_days"), force=bool(payload.get("force", False)), ) return jsonify(to_plain(status)) except ValueError as exc: return jsonify({"detail": str(exc)}), 400 except RuntimeError as exc: return jsonify({"detail": str(exc)}), 400 @historical_blueprint.post("/historical/sync-now") def historical_sync_now(): try: status = service.start(auto=True) return jsonify(to_plain(status)) except RuntimeError as exc: return jsonify({"detail": str(exc)}), 400 @historical_blueprint.post("/historical/cancel") def historical_cancel(): return jsonify(to_plain(service.cancel())) def _parse_date(value: str | None) -> date | None: if not value: return None return date.fromisoformat(value)