from __future__ import annotations

from datetime import datetime
from http import HTTPStatus


class SystemRoutesMixin:
    def _handle_system_public_get(self, parsed) -> bool:
        if parsed.path == "/api/health":
            self.send_json(
                {
                    "ok": True,
                    "storage": "sqlite",
                    "account_required": True,
                    "time": datetime.now().astimezone().isoformat(timespec="seconds"),
                }
            )
            return True
        return False

    def _handle_system_get(self, parsed) -> bool:
        if parsed.path == "/api/admin/settings":
            self.send_json(
                {"ok": True, **self.application_service.system_status(), "users": self.application_service.admin_users()}
            )
            return True
        return False

    def backfill_data(self) -> None:
        try:
            body = self.read_json_body()
            lookback_raw = body.get("lookback")
            lookback = int(lookback_raw) if lookback_raw not in (None, "") else None
            audit = self.application_service.backfill(
                str(body.get("start_date") or ""),
                str(body.get("end_date") or ""),
                lookback=lookback,
                dry_run=bool(body.get("dry_run")),
                force=bool(body.get("force")),
                create_backup=body.get("create_backup", True) is not False,
            )
            self.send_json({"ok": True, **audit, "results": audit.get("results") or []})
        except ValueError as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
        except Exception as exc:
            self.send_json({"error": f"历史回补失败：{exc}"}, HTTPStatus.INTERNAL_SERVER_ERROR)
