import asyncio import re from datetime import datetime, timedelta from typing import Optional from fastapi import APIRouter, Depends, Query from common.database.model.models import SkyScore from common.enums import ErrorType, SkyGrade from common.logger import LOG from common.models.errors import error_info from common.utils.kma_time import KST, now_kst from router.v1.watch.protocol import Res_WatchSummary, WatchEvent, WatchNow, WatchSlot, WatchSunset, WatchTimeline from services.calc.sky_score import GRADE_LABEL from services.calc.sun import sun_times from services.feed_service import _SUNSET_FULL, _top, feed_ttl_sec, slot_of from services.index_service import IndexService from services.now_service import NowService from services.sky_service import SkyService from services.weather_service import WeatherService from services.week_service import EventItem, WeekService router = APIRouter(prefix="/v1/watch", tags=["watch"]) MAX_PICKS = 3 # 워치 스킨이 큰 원(1위) + 둘레 링 6개(2~7위)를 채운다 TOP_N = 7 MAX_EVENTS = 2 # 워치 readTimeout(10초) 안에 끝나도록. 첫 조회라 TourAPI 를 부르다 늦으면 이번 요약엔 축제를 빼고, 캐시는 다음 조회가 채운다 EVENTS_TIMEOUT_SEC = 4 # "[하트하트아트앤컬처] 마음의 각도" 처럼 이름 앞 주최·분류 괄호. 워치 칸이 좁아 뺀다 _NAME_PREFIX = re.compile(r"^(\[[^\]]*\]\s*)+") def _best(score: SkyScore, kind: str) -> datetime: return datetime.fromisoformat(next(b["at"] for b in score.best_times if b["kind"] == kind)).astimezone(KST) async def _events(week: WeekService, region: str) -> tuple[ErrorType, list[EventItem]]: try: return await asyncio.wait_for(week.events(region, None), EVENTS_TIMEOUT_SEC) except TimeoutError: LOG.warning(f"[watch] events {region}: {EVENTS_TIMEOUT_SEC}초 넘어 생략") return ErrorType.EXTERNAL_API_ERROR, [] def timeline(now: datetime, sunset: Optional[SkyScore], is_today: bool) -> list[WatchTimeline]: """컴플리케이션이 언제 무엇을 보여줄지. 오늘 노을이 볼 만하면(60점 이상) 일몰 2시간 전부터 보랏빛 하늘까지 노을, 나머지는 각.""" if sunset is None or not is_today or sunset.score < _SUNSET_FULL: return [WatchTimeline(start_at=now, kind="gak")] start, end = _best(sunset, "sun") - timedelta(hours=2), _best(sunset, "twilight") if now >= end: return [WatchTimeline(start_at=now, kind="gak")] items = [WatchTimeline(start_at=now, kind="gak")] if now < start else [] return items + [WatchTimeline(start_at=max(start, now), kind="sunset"), WatchTimeline(start_at=end, kind="gak")] @router.get("/summary", response_model=Res_WatchSummary, response_model_exclude_none=True, summary="워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표") async def get_watch_summary( region: str = Query(..., description="구 행정코드"), pick: Optional[str] = Query(None, description="내 각 코드, 쉼표로 최대 3개 (예: running,laundry)"), weather: WeatherService = Depends(), now_service: NowService = Depends(), sky: SkyService = Depends(), index: IndexService = Depends(), week: WeekService = Depends(), ) -> Res_WatchSummary: (err_t, today), (err_n, now_w), (err_s, view), (err_i, board), (err_e, events) = await asyncio.gather( weather.today(region), now_service.now(region), sky.view(region), index.board(region), _events(week, region), ) today = today if err_t is ErrorType.SUCCESS else None now_w = now_w if err_n is ErrorType.SUCCESS else None view = view if err_s is ErrorType.SUCCESS else None board = board if err_i is ErrorType.SUCCESS else None found = next((x.region for x in (today, now_w, view, board) if x is not None), None) if found is None: return Res_WatchSummary(result=error_info(err_t)) now = now_kst() sunset_at = sun_times(now.date(), float(found.lat), float(found.lon)).sunset_at res = Res_WatchSummary( region_code=found.code, region_name=found.name, issued_at=now, refresh_at=now + timedelta(seconds=feed_ttl_sec(now, sunset_at)), mode=slot_of(now, sunset_at), ) if today is not None: past = [s for s in today.slots if s.at <= now] cur = past[-1] if past else (today.slots[0] if today.slots else None) if cur is not None: res.now = WatchNow(temp_c=float(cur.row.temp_c) if cur.row else None, icon=cur.icon) res.slots = [ WatchSlot(at=s.at.astimezone(KST), icon=s.icon, temp_c=float(s.row.temp_c) if s.row else None, rain_prob=s.row.rain_prob if s.row else None) for s in today.slots if s.at > now ] if now_w is not None: res.now = (res.now or WatchNow()).model_copy(update={"rain_2h": now_w.will_rain_2h, "thunder": now_w.thunder_2h, "text": now_w.rain_2h_text}) res.warning = now_w.warnings[0].text if now_w.warnings else None if board is not None: res.top = [_top(i) for i in board.ranked[:TOP_N]] codes = [c.strip() for c in (pick or "").split(",") if c.strip()][:MAX_PICKS] by_code = {i.definition.code: i for i in board.items} res.picks = [_top(by_code[c]) for c in codes if c in by_code] target, is_today = None, False if view is not None: is_today = now < sunset_at target = view.sunset if is_today else next((x for x in view.days if x.score_date > now.date()), None) if target is not None: res.sunset = WatchSunset( is_today=is_today, score=target.score, grade_label=GRADE_LABEL[SkyGrade(target.grade)], sunset_at=_best(target, "sun"), best_at=_best(target, "peak"), ) res.timeline = timeline(now, target, is_today) # 축제를 못 가져와도 요약은 그대로 낸다 (err_e 면 빈 목록) if err_e is ErrorType.SUCCESS: res.events = [ WatchEvent(name=_NAME_PREFIX.sub("", i.event.name) or i.event.name, place_name=i.event.place_name, status_label=i.status_label, fit=i.fit) # 진행 중인 행사를 먼저 (스킨은 첫 번째 하나만 보여 준다). 같은 상태 안에서는 서버 순서(가까운 날짜·거리) 그대로 for i in sorted(events, key=lambda i: i.status != "live")[:MAX_EVENTS] ] return res