from dataclasses import dataclass, field from datetime import date, time, timedelta from typing import Literal, Optional from fastapi import Depends from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import User, WeatherDaily, WeatherHourly from common.enums import ErrorType, RainType, Sky from common.utils.kma_time import KST, kst_midnight, now_kst from crud.region_crud import RegionCRUD from crud.weather_crud import WeatherCRUD from crud.week_crud import WeekCRUD from services import saju_text as T from services.level_service import award, level_of, unlock_level from services.saju.climate import HourWeather, chart_climate, climate_match from services.saju.daily import DailyFacts, daily_facts, interactions from services.saju.ganji import branch_element, ko, stem_element from services.saju.pillars import Chart, Pillar, make_chart from services.saju.rules import branch_relations, stem_relations, ten_god from services.weather_service import WeatherService from services.week_service import WeekService Gender = Literal["male", "female"] WEEK_DAYS = 7 # 오늘 점수 = 사주 점수 + (날씨 궁합 − 50) × 이 비율. 화면 점수는 평균 68 쯤에서 퍼지게 늘린다 (날씨 점수처럼 50 이 '나쁨'으로 읽히지 않게) WEATHER_SHARE = 0.6 SHOW_CENTER, SHOW_SPREAD, SHOW_MIN, SHOW_MAX = 68, 1.2, 25, 98 RIVALS = ("비견", "겁재") CROWDED = 3 # 원국에 비겁이 이만큼 이상이면 비겁 날 돈 조심 (군겁쟁재) _WEEKDAY = "월화수목금토일" _SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"} @dataclass class DayWeather: hours: list[HourWeather] icon: str word: str temp_min: Optional[int] temp_max: Optional[int] by_hour: dict[int, tuple[float, str]] = field(default_factory=dict) # 시각 → (기온, 하늘 말) @dataclass class DayReading: day: date facts: DailyFacts weather: Optional[DayWeather] climate_score: Optional[int] best_hours: tuple[int, ...] reasons: tuple[dict, ...] score: int @dataclass class Card: kind: str # when·do·avoid·good·wear title: str body: str sub: Optional[str] = None @dataclass class Reading: chart: Chart scene: tuple[str, str] scene_icon: str need: list[str] today: DayReading cards: list[Card] why: list[str] level: int logged_in: bool week: Optional[list[DayReading]] = None money: Optional[str] = None work: Optional[str] = None love: Optional[dict] = None month: Optional[dict] = None year: Optional[dict] = None def _icon(sky: Sky, rain: RainType) -> str: if rain is RainType.SNOW: return "snow" if rain is not RainType.NONE: return "rain" return {Sky.CLEAR: "sun", Sky.PARTLY: "sun_cloud", Sky.CLOUDY: "cloud"}[sky] def _word(sky: Sky, rain: RainType) -> str: return "눈" if rain is RainType.SNOW else "비" if rain is not RainType.NONE else _SKY_WORD[sky] def hourly_weather(rows: list[WeatherHourly]) -> Optional[DayWeather]: """시간별 예보 → 06~21시 날씨. 칸이 모자라면 None""" rows = [r for r in rows if 6 <= r.forecast_at.astimezone(KST).hour <= 21] if len(rows) < 6: return None hours = [HourWeather(hour=r.forecast_at.astimezone(KST).hour, feels_c=float(r.feels_c), humidity=float(r.humidity), raining=r.rain_type != RainType.NONE.value) for r in rows] wet = [RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value] noon = min(rows, key=lambda r: abs(r.forecast_at.astimezone(KST).hour - 14)) rain = wet[0] if wet else RainType.NONE temps = [float(r.temp_c) for r in rows] return DayWeather( hours=hours, icon=_icon(Sky(noon.sky), rain), word=_word(Sky(noon.sky), rain), temp_min=round(min(temps)), temp_max=round(max(temps)), by_hour={r.forecast_at.astimezone(KST).hour: (float(r.temp_c), _word(Sky(r.sky), RainType(r.rain_type))) for r in rows}, ) def daily_weather(d: WeatherDaily) -> Optional[DayWeather]: """중기예보(하루 최저·최고)로 06~21시를 어림한다: 6시 최저 → 15시 최고 → 21시 중간""" if d.temp_min_c is None or d.temp_max_c is None: return None lo, hi = float(d.temp_min_c), float(d.temp_max_c) rain = RainType(d.rain_type) wet = rain is not RainType.NONE or d.rain_prob >= 60 hours = [] for h in range(6, 22): t = lo + (hi - lo) * (h - 6) / 9 if h <= 15 else hi - (hi - lo) * (h - 15) / 12 hours.append(HourWeather(hour=h, feels_c=t, humidity=85 if wet else 55, raining=wet)) return DayWeather(hours=hours, icon=_icon(Sky(d.sky), rain), word=_word(Sky(d.sky), rain), temp_min=round(lo), temp_max=round(hi)) def shown_saju(saju: int) -> int: return max(SHOW_MIN, min(SHOW_MAX, round(SHOW_CENTER + (saju - 50) * SHOW_SPREAD))) def weather_points(climate: Optional[int]) -> Optional[int]: return None if climate is None else round((climate - 50) * WEATHER_SHARE * SHOW_SPREAD) def total_score(saju: int, climate: Optional[int]) -> int: return max(SHOW_MIN, min(SHOW_MAX, shown_saju(saju) + (weather_points(climate) or 0))) def window_text(best: tuple[int, ...]) -> str: """좋은 시각들 → '오후 1~4시' / '오전 11시~오후 2시' / '오후 3시 전후'""" if not best: return "" lo, hi = min(best), max(best) + 1 if lo + 1 == hi: return f"{T.hour_word(lo)} 전후" a, b = T.hour_word(lo).split(" "), T.hour_word(hi).split(" ") return f"{a[0]} {a[1][:-1]}~{b[1]}" if a[0] == b[0] else f"{a[0]} {a[1]}~{b[0]} {b[1]}" def _pillars(chart: Chart) -> dict[str, Pillar]: out = {"year": chart.year, "month": chart.month, "day": chart.day} if chart.hour is not None: out["hour"] = chart.hour return out def crowded_rivals(chart: Chart) -> bool: """원국에 비견·겁재(일간 포함)가 많은지""" me = chart.day.stem stems = [p.stem for p in _pillars(chart).values()] branches = [p.branch for p in _pillars(chart).values()] n = sum(1 for s in stems if ten_god(me, s) in RIVALS) + sum(1 for b in branches if stem_element(me) == branch_element(b)) return n >= CROWDED def why_words(facts: DailyFacts) -> list[str]: """점수에 가장 크게 작용한 사실 셋을 사람 말로""" out = [] for c in sorted(facts.contributions, key=lambda c: -abs(c.points))[:3]: place = f"{T.PLACE_WORD[c.position]} 자리와 " if c.position else "" sign = "+" if c.points >= 0 else "−" out.append(f"{place}{c.fact}({'·'.join(ko(ch) for ch in c.chars)}) {sign}{abs(round(c.points))}") return out def _rel(i) -> str: return f"{T.PLACE_WORD[i.position]} 자리와 {i.relation.kind}({'·'.join(ko(ch) for ch in i.relation.chars)})" def avoid_card(chart: Chart, facts: DailyFacts) -> Optional[Card]: """조심할 것 두 가지까지: 돈(군겁쟁재)과 가장 무거운 관계 (나·연인 자리 먼저)""" lines, subs = [], [] if facts.stem_ten_god in RIVALS and crowded_rivals(chart): lines.append(T.CROWDED_RIVALS) subs.append(f"원국에 같은 기운이 많은 날 {T.josa(facts.stem_ten_god, '이가')} 들어와요") bad = sorted((i for i in facts.interactions if i.relation.kind in {k for k, _ in T.AVOID_TEXT}), key=lambda i: 0 if i.position == "day" else 1) for i in bad: body = T.AVOID_TEXT.get((i.relation.kind, i.position)) or T.AVOID_TEXT.get((i.relation.kind, "")) if body and body not in lines: lines.append(body) subs.append(_rel(i)) break if not lines: return None return Card(kind="avoid", title="오늘 조심할 것", body="\n".join(lines[:2]), sub=" · ".join(subs[:2])) def good_card(facts: DailyFacts) -> Optional[Card]: good = sorted((i for i in facts.interactions if i.relation.kind in T.GOOD_RELATIONS), key=lambda i: 0 if i.position == "day" else 1) if not good: return None i = good[0] return Card(kind="good", title="오늘 좋은 흐름", body=T.GOOD_TEXT[i.position], sub=_rel(i)) def when_card(r: DayReading) -> Optional[Card]: if not r.best_hours or r.weather is None: return None h = r.best_hours[0] temp, word = r.weather.by_hour.get(h, (None, r.weather.word)) helps = [T.NEED_WORD[(x["axis"], x["need"])] for x in r.reasons if x.get("helps") and (x["axis"], x["need"]) in T.NEED_WORD] body = f"내 기운에 필요한 {T.josa('·'.join(helps), '이가')} 가장 많이 오는 때예요. 중요한 일은 이때 하세요." if helps else "오늘 날씨가 내 기운과 가장 무난한 때예요. 중요한 일은 이때 하세요." sub = f"{word} {round(temp)}°" if temp is not None else word return Card(kind="when", title=window_text(r.best_hours), body=body, sub=sub) def needs_of(chart_need: dict) -> list[tuple[str, str]]: """조후에서 채워야 할 축 (순한 축은 뺀다)""" return [(a, n) for a, n in chart_need.items() if n != "mild"] def wear_card(r: DayReading, needs: list[tuple[str, str]], place: Optional[str]) -> Optional[Card]: if r.weather is None: return None feels = min(h.feels_c for h in r.weather.hours) color = T.NEED_COLOR[needs[0]] if needs else None body = f"아침저녁 체감 {round(feels)}°라 {T.clothes(feels)}" + (f", 색은 {color} 포인트" if color else "") return Card(kind="wear", title="입을 것 · 갈 곳", body=body, sub=f"갈 곳: {place}" if place else None) def love_week(chart: Chart, week: list[DayReading], gender: Optional[Gender]) -> dict: """이번 주 연애 기운이 좋은 날과 조심할 날. 비 오는 날은 좋은 날에서 뒤로""" goods, bads = [], [] for r in week: kinds = set() for x in r.facts.love.reasons: k = x["kind"] if k == "일지": rel = x.get("relation") (kinds.add("일지합") if rel in ("육합", "반합", "삼합") else bads.append((r, rel))) else: kinds.add(k) good = [k for k in ("도화", "홍염", "일지합", "재성", "관성") if k in kinds] if good: goods.append((r, good)) goods.sort(key=lambda g: (g[0].weather is not None and g[0].weather.icon in ("rain", "snow"), -g[0].score)) out: dict = {"gender": gender} if goods: r, kinds = goods[0] rainy = r.weather is not None and r.weather.icon in ("rain", "snow") out["good"] = {"day": r.day, "weekday": _WEEKDAY[r.day.weekday()], "icon": r.weather.icon if r.weather else None, "word": r.weather.word if r.weather else None, "temp_max": r.weather.temp_max if r.weather else None, "body": T.LOVE_GOOD[kinds[0]] + (" " + T.LOVE_RAINY if rainy else ""), "why": "·".join(kinds)} if bads: r, rel = bads[0] out["caution"] = {"day": r.day, "weekday": _WEEKDAY[r.day.weekday()], "body": T.LOVE_BAD.get(rel, "말을 한 번 더 고르세요."), "why": f"나·연인 자리와 {rel}"} return out def period(chart: Chart, p: Pillar, unit: str) -> dict: """이달·올해: 그 간지 천간 십성 + 원국과의 관계""" god = ten_god(chart.day.stem, p.stem) title, body = (T.MONTH_TEXT if unit == "달" else T.YEAR_TEXT)[god] return {"pillar": ko(p.stem + p.branch), "ten_god": god, "title": title, "body": body, "notes": [_rel(i) for i in interactions(chart, p)]} @dataclass class Match: score: int title: str lines: list[str] day: Optional[DayReading] # 이번 주 둘 다 좋은 날 friend_scene: str MATCH_SCORE = {"base": 55, "stem_hap": 12, "resource": 8, "wealth": 5, "output": 5, "rival": 2, "officer": 0, "branch_hap": 8, "branch_bad": -8, "climate_ok": 10} def match_reading(me: Chart, friend: Chart, my_days: list[DayReading], friend_days: list[DayReading]) -> Match: god = ten_god(me.day.stem, friend.day.stem) title, body = next(v for k, v in T.MATCH_TEXT.items() if god in k) group = next(g for k, g in (("비견겁재", "rival"), ("식신상관", "output"), ("편재정재", "wealth"), ("편관정관", "officer"), ("편인정인", "resource")) if god in k) score, lines = MATCH_SCORE["base"] + MATCH_SCORE[group], [body] if any(r.kind == "천간합" for r in stem_relations(me.day.stem, friend.day.stem)): score += MATCH_SCORE["stem_hap"] lines.append(T.MATCH_STEM_HAP) for r in branch_relations(me.day.branch, friend.day.branch): if r.kind in T.MATCH_BRANCH: score += MATCH_SCORE["branch_hap"] if r.kind in ("육합", "반합") else MATCH_SCORE["branch_bad"] lines.append(T.MATCH_BRANCH[r.kind]) break a, b = chart_climate(me), chart_climate(friend) if a.temp * b.temp < 0 or a.moist * b.moist < 0: score += MATCH_SCORE["climate_ok"] lines.append(T.MATCH_CLIMATE_OK) else: need = [T.NEED_WORD[n] for n in needs_of(a.need)] if need: lines.append(T.MATCH_CLIMATE_SAME.format(need=T.josa("·".join(need), "이가"))) both = [(x, y) for x, y in zip(my_days, friend_days)] best = max(both, key=lambda p: min(p[0].score, p[1].score))[0] if both else None return Match(score=max(0, min(100, score)), title=title, lines=lines, day=best, friend_scene=T.SCENES[(b.season, b.label)][0]) class SajuService: def __init__( self, regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD), week_crud: WeekCRUD = Depends(WeekCRUD), weather_service: WeatherService = Depends(WeatherService), week: WeekService = Depends(WeekService), ) -> None: self.regions, self.weather, self.week_crud, self.weather_service, self.week = regions, weather, week_crud, weather_service, week async def _weather(self, region_code: str, start: date) -> tuple[ErrorType, dict[date, DayWeather]]: err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code)) if err is not ErrorType.SUCCESS: return err, {} if region is None: return ErrorType.NOT_FOUND, {} await self.weather_service.ensure_vilage(region, now_kst()) t0 = kst_midnight(start) err, hourly = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region.code, t0, t0 + timedelta(days=WEEK_DAYS))) if err is not ErrorType.SUCCESS: return err, {} err, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.week_crud.daily(s, region.code, start, start + timedelta(days=WEEK_DAYS - 1))) if err is not ErrorType.SUCCESS: return err, {} out: dict[date, DayWeather] = {} for i in range(WEEK_DAYS): d = start + timedelta(days=i) w = hourly_weather([r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d]) if w is None: dd = next((x for x in daily or [] if x.forecast_date == d), None) w = daily_weather(dd) if dd else None if w is not None: out[d] = w return ErrorType.SUCCESS, out def _day(self, chart: Chart, d: date, w: Optional[DayWeather], gender: Optional[Gender]) -> DayReading: facts = daily_facts(chart, d, gender) if w is None: return DayReading(day=d, facts=facts, weather=None, climate_score=None, best_hours=(), reasons=(), score=facts.score) m = climate_match(chart, w.hours) return DayReading(day=d, facts=facts, weather=w, climate_score=m.score, best_hours=m.best_hours, reasons=m.reasons, score=total_score(facts.score, m.score)) async def match( self, me: tuple[date, Optional[time], float], friend: tuple[date, Optional[time], float], region_code: str, user: Optional[User], ) -> tuple[ErrorType, Optional[Match]]: """궁합 (레벨 5부터, 로그인 필요)""" if user is None or level_of(user.points) < unlock_level("saju_match"): return ErrorType.AUTH_REQUIRED if user is None else ErrorType.LEVEL_REQUIRED, None try: a, b = make_chart(*me), make_chart(*friend) except ValueError: return ErrorType.INVALID_INPUT, None today = now_kst().date() err, weather = await self._weather(region_code, today) if err is not ErrorType.SUCCESS: return err, None ds = [today + timedelta(days=i) for i in range(WEEK_DAYS)] return ErrorType.SUCCESS, match_reading(a, b, [self._day(a, d, weather.get(d), None) for d in ds], [self._day(b, d, weather.get(d), None) for d in ds]) async def reading( self, birth_date: date, birth_time: Optional[time], longitude: float, gender: Optional[Gender], region_code: str, user: Optional[User], ) -> tuple[ErrorType, Optional[Reading]]: try: chart = make_chart(birth_date, birth_time, longitude) except ValueError: return ErrorType.INVALID_INPUT, None today = now_kst().date() err, weather = await self._weather(region_code, today) if err is not ErrorType.SUCCESS: return err, None days = [self._day(chart, today + timedelta(days=i), weather.get(today + timedelta(days=i)), gender) for i in range(WEEK_DAYS)] r0 = days[0] m0 = climate_match(chart, r0.weather.hours) if r0.weather else None chart_climate = m0.chart if m0 else None scene = T.SCENES[(chart_climate.season, chart_climate.label)] if chart_climate else ("", "") needs = needs_of(chart_climate.need) if chart_climate else [] _, places, _, _ = await self.week.places(region_code, today, None) place = next((p.place.name for p in places if p.is_good), places[0].place.name if places else None) todo = T.TEN_GOD_TEXT[r0.facts.stem_ten_god][1] cards = [c for c in (when_card(r0), Card(kind="do", title="오늘 할 것", body=todo, sub=f"오늘은 {T.josa(r0.facts.stem_ten_god, '이가')} 들어오는 날"), avoid_card(chart, r0.facts), good_card(r0.facts), wear_card(r0, needs, place)) if c] level = 1 if user is not None: total = await award(user.user_id, "saju") level = level_of(total or user.points) def unlocked(key: str) -> bool: return user is not None and level >= unlock_level(key) now_chart = make_chart(today, time(12, 0)) return ErrorType.SUCCESS, Reading( chart=chart, scene=scene, scene_icon=T.SCENE_ICON.get(chart_climate.label, "sun") if chart_climate else "sun", need=[T.NEED_WORD[n] for n in needs], today=r0, cards=cards, why=why_words(r0.facts), level=level, logged_in=user is not None, week=days if unlocked("saju_week") else None, money=T.MONEY_TEXT[r0.facts.stem_ten_god] if unlocked("saju_money") else None, work=T.WORK_TEXT[r0.facts.stem_ten_god] if unlocked("saju_money") else None, love=love_week(chart, days, gender) if unlocked("saju_love") else None, month={**period(chart, now_chart.month, "달"), "from": now_chart.jeol.at.date(), "until": now_chart.next_jeol.at.date(), "jeol": now_chart.jeol.name} if unlocked("saju_month") else None, year={**period(chart, now_chart.year, "해"), "year": today.year} if unlocked("saju_year") else None, )