from __future__ import annotations import json import os import time from dataclasses import dataclass from pathlib import Path from typing import Any from douyin.core import path_config @dataclass class DashboardData: cfg: dict[str, Any] run_log: list[str] action_log: list[str] reservations: list[dict[str, Any]] high_value_rooms: list[dict[str, Any]] mapping_rows: list[dict[str, Any]] win_images: list[Path] screenshot_path: Path | None ocr_files: list[Path] def _read_json(path: str | Path, default: Any) -> Any: try: with open(path, "r", encoding="utf-8") as f: return json.load(f) except Exception: return default def _tail(path: str | Path, limit: int = 220) -> list[str]: try: with open(path, "r", encoding="utf-8", errors="replace") as f: lines = f.readlines()[-limit:] return [line.rstrip("\n") for line in lines if line.strip()] except Exception: return [] def _list_images(path: str | Path, limit: int = 40) -> list[Path]: root = Path(path) if not root.exists(): return [] items = [ p for p in root.iterdir() if p.is_file() and p.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp"} ] items.sort(key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True) return items[:limit] def _normalize_rows(raw: Any, keys: tuple[str, ...]) -> list[dict[str, Any]]: if isinstance(raw, dict): for key in keys: value = raw.get(key) if isinstance(value, list): return [x for x in value if isinstance(x, dict)] return [raw] if raw else [] if isinstance(raw, list): return [x for x in raw if isinstance(x, dict)] return [] def _mapping_rows() -> list[dict[str, Any]]: raw = _read_json(Path(path_config.get_project_root()) / "douyin" / "core" / "state" / "room_pos_map.json", {}) rows: list[dict[str, Any]] = [] if isinstance(raw, dict): source = raw.get("items") if isinstance(raw.get("items"), list) else raw if isinstance(source, dict): iterable = source.items() else: iterable = enumerate(source if isinstance(source, list) else []) for key, value in iterable: if str(key).startswith("_"): continue if isinstance(value, dict): rows.append({ "pos": value.get("pos") or value.get("room_pos") or key, "title": value.get("title") or value.get("room_title") or value.get("raw_title") or "-", "status": value.get("status") or value.get("state") or "已记录", "updated": value.get("updated_at") or value.get("ts") or value.get("time") or "-", }) else: rows.append({"pos": key, "title": str(value), "status": "已记录", "updated": "-"}) return rows[:80] def load_dashboard_data() -> DashboardData: cfg_path = path_config.get_config_path() cfg = _read_json(cfg_path, {}) reservations_raw = _read_json(path_config.get_reservations_path(), {}) high_raw = _read_json(path_config.get_high_value_rooms_path(), {}) pic_dir = Path(path_config.get_pic_dir()) screenshot = Path(path_config.get_screenshot_path()) return DashboardData( cfg=cfg if isinstance(cfg, dict) else {}, run_log=_tail(path_config.get_log_file_path(), 240) or _tail(path_config.get_simple_log_path(), 240), action_log=_tail(path_config.get_actions_log_path(), 240), reservations=_normalize_rows(reservations_raw, ("reservations", "items", "queue")), high_value_rooms=_normalize_rows(high_raw, ("rooms", "items", "records")), mapping_rows=_mapping_rows(), win_images=_list_images(pic_dir / "lottery_prize_captures", 60), screenshot_path=screenshot if screenshot.exists() else None, ocr_files=sorted((pic_dir / "ocr").glob("*"), key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True)[:20] if (pic_dir / "ocr").exists() else [], ) def cfg_get(cfg: dict[str, Any], *keys: str, default: Any = "-") -> Any: cur: Any = cfg for key in keys: if not isinstance(cur, dict) or key not in cur: return default cur = cur[key] return cur def fmt_ts(value: Any) -> str: try: ts = float(value) if ts <= 0: return "-" return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts)) except Exception: return str(value or "-")