fishin 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fishin/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """fishin — terminal solunar, tide & weather forecast."""
2
+
3
+ __version__ = "0.2.1"
fishin/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
fishin/astro.py ADDED
@@ -0,0 +1,283 @@
1
+ """Astronomy and day-building.
2
+
3
+ Pure computation — no terminal output, no argparse. Given a date, lat/lon, and
4
+ timezone, returns a dict describing the day's solunar events, periods, and
5
+ rating. The skyfield ephemeris is loaded lazily and cached at module scope so
6
+ multi-day runs don't repay the cost.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ import os
13
+ from datetime import datetime, timedelta, date
14
+ from pathlib import Path
15
+ from zoneinfo import ZoneInfo
16
+
17
+ from skyfield.api import Loader, wgs84
18
+ from skyfield import almanac
19
+
20
+
21
+ MAJOR_HOURS = 3.0 # 1.5hr each side of moon transit / antitransit
22
+ MINOR_HOURS = 2.0 # 1hr each side of moonrise / moonset
23
+
24
+ _ts = None
25
+ _eph = None
26
+
27
+
28
+ def _ephemeris_dir() -> Path:
29
+ base = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
30
+ return base / "fishin" / "ephemeris"
31
+
32
+
33
+ def _load_skyfield():
34
+ """Lazy-load skyfield's timescale and the DE421 ephemeris.
35
+
36
+ The ~17MB ephemeris is parked under `~/.cache/fishin/ephemeris/` so it
37
+ doesn't litter whatever directory the user happens to run `fishin` from,
38
+ and so it survives across invocations.
39
+ """
40
+ global _ts, _eph
41
+ if _ts is None:
42
+ path = _ephemeris_dir()
43
+ path.mkdir(parents=True, exist_ok=True)
44
+ loader = Loader(str(path))
45
+ _ts = loader.timescale()
46
+ _eph = loader("de421.bsp")
47
+ return _ts, _eph
48
+
49
+
50
+ # ---------------------------------------------------------------- moon phase
51
+
52
+ def phase_name(deg: float) -> tuple[str, str]:
53
+ """Return (name, symbol). Named phases (New, Quarters, Full) get tight ±5°
54
+ windows; crescent / gibbous fill the gaps."""
55
+ a = deg % 360
56
+ if a < 5 or a >= 355:
57
+ return "New Moon", "🌑"
58
+ if a < 85:
59
+ return "Waxing Crescent", "🌒"
60
+ if a < 95:
61
+ return "First Quarter", "🌓"
62
+ if a < 175:
63
+ return "Waxing Gibbous", "🌔"
64
+ if a < 185:
65
+ return "Full Moon", "🌕"
66
+ if a < 265:
67
+ return "Waning Gibbous", "🌖"
68
+ if a < 275:
69
+ return "Last Quarter", "🌗"
70
+ return "Waning Crescent", "🌘"
71
+
72
+
73
+ def phase_score(deg: float) -> float:
74
+ # 1.0 at new and full, 0.0 at quarters
75
+ return abs(math.cos(math.radians(deg)))
76
+
77
+
78
+ # ---------------------------------------------------------------- events
79
+
80
+ def find_events(target_date: date, lat: float, lon: float, tz: ZoneInfo) -> dict:
81
+ ts, eph = _load_skyfield()
82
+ location = wgs84.latlon(lat, lon)
83
+
84
+ start_local = datetime(target_date.year, target_date.month, target_date.day,
85
+ tzinfo=tz)
86
+ end_local = start_local + timedelta(days=1)
87
+ pad = timedelta(hours=4)
88
+
89
+ t0 = ts.from_datetime(start_local - pad)
90
+ t1 = ts.from_datetime(end_local + pad)
91
+
92
+ def in_day(t):
93
+ local = t.utc_datetime().astimezone(tz)
94
+ return start_local <= local < end_local
95
+
96
+ # Sunrise / sunset
97
+ f_sun = almanac.sunrise_sunset(eph, location)
98
+ sun_times, sun_events = almanac.find_discrete(t0, t1, f_sun)
99
+ sunrise = next((t for t, e in zip(sun_times, sun_events) if e == 1 and in_day(t)), None)
100
+ sunset = next((t for t, e in zip(sun_times, sun_events) if e == 0 and in_day(t)), None)
101
+
102
+ # Moonrise / moonset
103
+ f_moon = almanac.risings_and_settings(eph, eph["moon"], location)
104
+ moon_times, moon_events = almanac.find_discrete(t0, t1, f_moon)
105
+ moonrise = next((t for t, e in zip(moon_times, moon_events) if e == 1 and in_day(t)), None)
106
+ moonset = next((t for t, e in zip(moon_times, moon_events) if e == 0 and in_day(t)), None)
107
+
108
+ # Sun meridian transit (solar noon)
109
+ f_sun_mt = almanac.meridian_transits(eph, eph["sun"], location)
110
+ smt, sme = almanac.find_discrete(t0, t1, f_sun_mt)
111
+ solar_noon = next((t for t, e in zip(smt, sme) if e == 1 and in_day(t)), None)
112
+
113
+ # Moon meridian transits: upper (overhead) and lower (antitransit, underfoot)
114
+ f_moon_mt = almanac.meridian_transits(eph, eph["moon"], location)
115
+ mmt, mme = almanac.find_discrete(t0, t1, f_moon_mt)
116
+ transits = [t for t, e in zip(mmt, mme) if e == 1 and in_day(t)]
117
+ antitransits = [t for t, e in zip(mmt, mme) if e == 0 and in_day(t)]
118
+
119
+ # Moon phase at local noon
120
+ noon = start_local + timedelta(hours=12)
121
+ phase_deg = almanac.moon_phase(eph, ts.from_datetime(noon)).degrees
122
+
123
+ def tolocal(t):
124
+ if t is None:
125
+ return None
126
+ return t.utc_datetime().astimezone(tz)
127
+
128
+ return {
129
+ "date": target_date,
130
+ "sunrise": tolocal(sunrise),
131
+ "solar_noon": tolocal(solar_noon),
132
+ "sunset": tolocal(sunset),
133
+ "moonrise": tolocal(moonrise),
134
+ "moonset": tolocal(moonset),
135
+ "transits": [tolocal(t) for t in transits],
136
+ "antitransits": [tolocal(t) for t in antitransits],
137
+ "phase_deg": phase_deg,
138
+ }
139
+
140
+
141
+ # ---------------------------------------------------------------- periods
142
+
143
+ def period_around(center: datetime, hours: float) -> tuple[datetime, datetime]:
144
+ half = timedelta(hours=hours / 2)
145
+ return (center - half, center + half)
146
+
147
+
148
+ def overlaps(a_start, a_end, b_start, b_end) -> bool:
149
+ return a_start < b_end and b_start < a_end
150
+
151
+
152
+ def build_day(target_date: date, lat: float, lon: float, tz_name: str) -> dict:
153
+ tz = ZoneInfo(tz_name)
154
+ ev = find_events(target_date, lat, lon, tz)
155
+
156
+ majors = []
157
+ for t in ev["transits"]:
158
+ majors.append(period_around(t, MAJOR_HOURS))
159
+ for t in ev["antitransits"]:
160
+ majors.append(period_around(t, MAJOR_HOURS))
161
+ majors.sort()
162
+
163
+ minors = []
164
+ if ev["moonrise"]:
165
+ minors.append(period_around(ev["moonrise"], MINOR_HOURS))
166
+ if ev["moonset"]:
167
+ minors.append(period_around(ev["moonset"], MINOR_HOURS))
168
+ minors.sort()
169
+
170
+ phase_pct = phase_score(ev["phase_deg"])
171
+ coincidence = 0.0
172
+ if ev["sunrise"] and ev["sunset"]:
173
+ win = timedelta(hours=1)
174
+ for p_start, p_end in majors + minors:
175
+ if overlaps(p_start, p_end, ev["sunrise"] - win, ev["sunrise"] + win):
176
+ coincidence += 0.15
177
+ if overlaps(p_start, p_end, ev["sunset"] - win, ev["sunset"] + win):
178
+ coincidence += 0.15
179
+ coincidence = min(coincidence, 0.4)
180
+
181
+ # Base 15% + phase up to 60% + coincidence up to 25%
182
+ score = min(1.0, 0.15 + 0.60 * phase_pct + 0.625 * coincidence)
183
+
184
+ if score >= 0.85:
185
+ rating = "Excellent"
186
+ elif score >= 0.65:
187
+ rating = "Good"
188
+ elif score >= 0.45:
189
+ rating = "Average"
190
+ else:
191
+ rating = "Poor"
192
+
193
+ pname, psymbol = phase_name(ev["phase_deg"])
194
+ return {**ev, "majors": majors, "minors": minors, "score": score,
195
+ "rating": rating, "phase_name": pname, "phase_symbol": psymbol}
196
+
197
+
198
+ # --------------------------------------------------------------- windows
199
+
200
+ # Window scoring: major/minor base + weighted overlap factors. Tuned so that
201
+ # a minor with two strong factors (e.g. sunrise + low tide) can outrank a lone
202
+ # major — which matches actual fishing wisdom.
203
+ _BASE_MAJOR = 4
204
+ _BASE_MINOR = 2
205
+ _W_SUN = 3 # sunrise or sunset within 1hr of the period
206
+ _W_TIDE = 2 # each H/L within 30min of the period
207
+ _W_CALM = 1
208
+ _W_WIND = -1
209
+ _W_RAIN = -2
210
+
211
+ _SUN_WIN = timedelta(hours=1)
212
+ _TIDE_WIN = timedelta(minutes=30)
213
+
214
+
215
+ def _weather_factor(day: dict, start: datetime, end: datetime) -> dict | None:
216
+ """Pick a single weather note for the window from the closest sample."""
217
+ wx = day.get("weather")
218
+ if not wx:
219
+ return None
220
+ midpoint = start + (end - start) / 2
221
+ samples = [p[1] for p in wx.get("periods", []) if p[1]]
222
+ if not samples:
223
+ return None
224
+ closest = min(samples, key=lambda s: abs(s["time"] - midpoint))
225
+
226
+ if closest["precip_prob"] >= 60:
227
+ return {"type": "weather", "subtype": "rain",
228
+ "value": closest["precip_prob"], "bonus": _W_RAIN}
229
+ if closest["wind_mph"] >= 18:
230
+ return {"type": "weather", "subtype": "wind",
231
+ "value": closest["wind_mph"], "bonus": _W_WIND}
232
+ if closest["wind_mph"] <= 6:
233
+ return {"type": "weather", "subtype": "calm",
234
+ "value": closest["wind_mph"], "bonus": _W_CALM}
235
+ return None
236
+
237
+
238
+ def _score_window(label: str, period: tuple, day: dict, base: int) -> dict:
239
+ s, e = period
240
+ score = base
241
+ factors: list[dict] = []
242
+
243
+ if day.get("sunrise") and overlaps(s, e,
244
+ day["sunrise"] - _SUN_WIN,
245
+ day["sunrise"] + _SUN_WIN):
246
+ factors.append({"type": "sunrise"})
247
+ score += _W_SUN
248
+ if day.get("sunset") and overlaps(s, e,
249
+ day["sunset"] - _SUN_WIN,
250
+ day["sunset"] + _SUN_WIN):
251
+ factors.append({"type": "sunset"})
252
+ score += _W_SUN
253
+
254
+ tide_events = (day.get("tides") or {}).get("events") or []
255
+ for ev in tide_events:
256
+ if overlaps(s, e, ev["time"] - _TIDE_WIN, ev["time"] + _TIDE_WIN):
257
+ factors.append({"type": "tide", "kind": ev["kind"],
258
+ "time": ev["time"], "height": ev["height"]})
259
+ score += _W_TIDE
260
+
261
+ wf = _weather_factor(day, s, e)
262
+ if wf:
263
+ factors.append(wf)
264
+ score += wf["bonus"]
265
+
266
+ return {"label": label, "period": period, "factors": factors, "score": score}
267
+
268
+
269
+ def evaluate_windows(day: dict) -> list[dict]:
270
+ """Score and rank every major/minor period for the day.
271
+
272
+ Returns a list of window dicts sorted by score descending (with earlier
273
+ starts breaking ties). Each window's `factors` list captures every overlap
274
+ (sunrise/sunset/tide/weather) that contributed to its score, so the
275
+ renderer can spell them out for the angler.
276
+ """
277
+ windows: list[dict] = []
278
+ for p in day.get("majors", []):
279
+ windows.append(_score_window("Major", p, day, _BASE_MAJOR))
280
+ for p in day.get("minors", []):
281
+ windows.append(_score_window("Minor", p, day, _BASE_MINOR))
282
+ windows.sort(key=lambda w: (-w["score"], w["period"][0]))
283
+ return windows
fishin/cache.py ADDED
@@ -0,0 +1,37 @@
1
+ """Disk-backed response cache for tide & weather fetches.
2
+
3
+ `diskcache` gives us a pickle-backed shelf with per-entry TTLs and zero ceremony.
4
+ Tide predictions are deterministic and cached for a year; weather forecasts get
5
+ 1h for today/future and a long TTL for past dates (forecasts no longer update).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from datetime import date
12
+ from functools import lru_cache
13
+ from pathlib import Path
14
+
15
+ import diskcache
16
+
17
+
18
+ YEAR_SECONDS = 365 * 24 * 3600
19
+ HOUR_SECONDS = 3600
20
+
21
+
22
+ def _cache_dir() -> Path:
23
+ base = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
24
+ return base / "fishin" / "responses"
25
+
26
+
27
+ @lru_cache(maxsize=1)
28
+ def get_cache() -> diskcache.Cache:
29
+ path = _cache_dir()
30
+ path.mkdir(parents=True, exist_ok=True)
31
+ return diskcache.Cache(str(path))
32
+
33
+
34
+ def weather_ttl(target_date: date) -> int:
35
+ """Past dates: forecast no longer updates, cache effectively forever.
36
+ Today/future: hourly model run, so 1h TTL keeps things fresh."""
37
+ return YEAR_SECONDS if target_date < date.today() else HOUR_SECONDS
fishin/cli.py ADDED
@@ -0,0 +1,274 @@
1
+ """Command-line entry point.
2
+
3
+ Resolves a location (flags → config file → built-in default → optional --city
4
+ geocode), then dispatches to one of four view modes:
5
+
6
+ fishin # single full panel for today
7
+ fishin 7 # compact list view, one row per day
8
+ fishin month # calendar grid for the month of --date
9
+ fishin best 14 # sorted ranking over the next N days
10
+
11
+ `--days N` (legacy) forces N full panels back-to-back.
12
+
13
+ Tide and weather fetches are coalesced into a single range request per mode
14
+ and cached on disk (see fishin.cache) — repeat runs are network-free, multi-day
15
+ modes pay one round-trip per service.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import calendar
22
+ from datetime import datetime, timedelta, date
23
+ from zoneinfo import ZoneInfo
24
+
25
+ from rich.console import Console
26
+
27
+ from .astro import build_day, evaluate_windows
28
+ from .render import render_day, render_list, render_month, render_best
29
+ from .tides import DEFAULT_STATION, get_tides_many, tide_curve
30
+ from .weather import get_weather_many
31
+ from .config import load_config, save_config, config_path
32
+
33
+
34
+ BACKSTOP = {
35
+ "lat": 27.3633,
36
+ "lon": -82.5197,
37
+ "tz": "America/New_York",
38
+ "station": DEFAULT_STATION,
39
+ "location": "Sarasota, FL",
40
+ }
41
+
42
+ # An ocean tide station >100km from the user's location is decoupled from
43
+ # their actual fishing conditions — inland lakes don't experience ocean tides.
44
+ # `--city` resolution drops the station entirely in that case.
45
+ INLAND_THRESHOLD_KM = 100.0
46
+
47
+
48
+ def _parse_date(s: str) -> date:
49
+ return datetime.strptime(s, "%Y-%m-%d").date()
50
+
51
+
52
+ def _resolve_city(query: str, console: Console) -> dict:
53
+ from .geocode import geocode, timezone_for
54
+ from .stations import nearest_station
55
+
56
+ hit = geocode(query)
57
+ lat, lon = hit["lat"], hit["lon"]
58
+ tz = timezone_for(lat, lon)
59
+ station = nearest_station(lat, lon)
60
+
61
+ pretty = hit["display_name"].split(",")
62
+ short = ", ".join(s.strip() for s in pretty[:2])
63
+
64
+ result = {"lat": lat, "lon": lon, "tz": tz, "location": short}
65
+
66
+ if station["distance_km"] <= INLAND_THRESHOLD_KM:
67
+ result["station"] = station["id"]
68
+ station_note = (f"station={station['id']} {station['name']} "
69
+ f"({station['distance_km']:.1f} km)")
70
+ else:
71
+ result["station"] = None
72
+ station_note = (f"inland — nearest tide station "
73
+ f"{station['name']} is "
74
+ f"{station['distance_km']:.0f} km away, "
75
+ f"tides disabled")
76
+
77
+ console.print(
78
+ f"[dim]resolved {query!r} → {short} "
79
+ f"({lat:.4f}, {lon:.4f}) tz={tz} {station_note}[/dim]"
80
+ )
81
+ return result
82
+
83
+
84
+ def _parse_mode(tokens: list[str], legacy_days: int) -> dict:
85
+ if not tokens:
86
+ return {"type": "panel", "days": legacy_days}
87
+ first = tokens[0].lower()
88
+ if first == "month":
89
+ return {"type": "month"}
90
+ if first == "best":
91
+ n = int(tokens[1]) if len(tokens) > 1 else 14
92
+ return {"type": "best", "days": n, "top": 5}
93
+ try:
94
+ n = int(first)
95
+ except ValueError as exc:
96
+ raise SystemExit(f"unknown mode {first!r}") from exc
97
+ return {"type": "list", "days": n}
98
+
99
+
100
+ def _build_days(loc: dict, tz: ZoneInfo, targets: list[date],
101
+ *, want_tides: bool, want_weather: bool,
102
+ console: Console) -> list[dict]:
103
+ """Bulk-fetch tides + weather for `targets`, attach to each day dict.
104
+
105
+ Tide fetches include ±1 day of padding around the request so each day's
106
+ cosine-interpolated curve can be anchored to its neighbours' extrema —
107
+ no more flat cold-start at midnight.
108
+ """
109
+ tides_by_day: dict[date, list[dict]] = {}
110
+ if want_tides and loc.get("station"):
111
+ try:
112
+ padded = (
113
+ [targets[0] - timedelta(days=1)]
114
+ + targets
115
+ + [targets[-1] + timedelta(days=1)]
116
+ )
117
+ tides_by_day = get_tides_many(loc["station"], padded, tz)
118
+ except Exception as exc:
119
+ console.print(f"[dim]tides unavailable ({exc})[/dim]")
120
+
121
+ weather_by_day: dict[date, dict] = {}
122
+ if want_weather:
123
+ try:
124
+ weather_by_day = get_weather_many(loc["lat"], loc["lon"], targets, tz)
125
+ except Exception as exc:
126
+ console.print(f"[dim]weather unavailable ({exc})[/dim]")
127
+
128
+ days: list[dict] = []
129
+ for target in targets:
130
+ day = build_day(target, loc["lat"], loc["lon"], loc["tz"])
131
+ events = tides_by_day.get(target, [])
132
+ if events:
133
+ prior = target - timedelta(days=1)
134
+ after = target + timedelta(days=1)
135
+ context: list[dict] = []
136
+ if tides_by_day.get(prior):
137
+ context.append(tides_by_day[prior][-1])
138
+ if tides_by_day.get(after):
139
+ context.append(tides_by_day[after][0])
140
+ day["tides"] = {
141
+ "station": loc["station"],
142
+ "events": events,
143
+ "curve": tide_curve(events, target, tz, n_points=48,
144
+ context=context),
145
+ }
146
+ if target in weather_by_day:
147
+ day["weather"] = weather_by_day[target]
148
+ day["windows"] = evaluate_windows(day)
149
+ days.append(day)
150
+ return days
151
+
152
+
153
+ def main(argv: list[str] | None = None) -> int:
154
+ parser = argparse.ArgumentParser(
155
+ prog="fishin",
156
+ description="Terminal solunar / tide / weather forecast",
157
+ )
158
+ parser.add_argument("mode", nargs="*",
159
+ help="N (list days) | 'month' | 'best [N]'")
160
+ parser.add_argument("--city", help="Place name to geocode")
161
+ parser.add_argument("--lat", type=float)
162
+ parser.add_argument("--lon", type=float)
163
+ parser.add_argument("--tz")
164
+ parser.add_argument("--location")
165
+ parser.add_argument("--station", help="NOAA CO-OPS tide station id")
166
+ parser.add_argument("--date", type=_parse_date, default=date.today())
167
+ parser.add_argument("--days", type=int, default=1,
168
+ help="Force N full panels (legacy)")
169
+ parser.add_argument("--no-tides", action="store_true")
170
+ parser.add_argument("--no-weather", action="store_true")
171
+ parser.add_argument("--save", action="store_true",
172
+ help=f"Persist resolved location to {config_path()}")
173
+ args = parser.parse_args(argv)
174
+
175
+ console = Console()
176
+
177
+ # If the config file is complete it's authoritative — don't blend in
178
+ # BACKSTOP's station/coords or they'll bleed into the user's actual
179
+ # location (e.g. Sarasota's tide station getting used for inland Austin).
180
+ config = load_config()
181
+ core = {"lat", "lon", "tz", "location"}
182
+ if core.issubset(config.keys()):
183
+ loc = config
184
+ else:
185
+ loc = dict(BACKSTOP)
186
+ loc.update(config)
187
+
188
+ if args.city:
189
+ try:
190
+ loc.update(_resolve_city(args.city, console))
191
+ except Exception as exc:
192
+ console.print(f"[red]could not resolve city {args.city!r}: {exc}[/red]")
193
+ return 1
194
+
195
+ for key in ("lat", "lon", "tz", "location", "station"):
196
+ v = getattr(args, key, None)
197
+ if v is not None:
198
+ loc[key] = v
199
+
200
+ if args.save:
201
+ path = save_config(loc)
202
+ console.print(f"[dim]saved → {path}[/dim]")
203
+
204
+ tz = ZoneInfo(loc["tz"])
205
+ mode = _parse_mode(args.mode, args.days)
206
+ want_tides = not args.no_tides
207
+ want_weather = not args.no_weather
208
+
209
+ if mode["type"] == "panel":
210
+ _run_panel(loc, tz, args.date, mode["days"],
211
+ want_tides=want_tides, want_weather=want_weather,
212
+ console=console)
213
+ elif mode["type"] == "list":
214
+ _run_list(loc, tz, args.date, mode["days"],
215
+ want_tides=want_tides, want_weather=want_weather,
216
+ console=console)
217
+ elif mode["type"] == "month":
218
+ _run_month(loc, args.date, console=console)
219
+ elif mode["type"] == "best":
220
+ _run_best(loc, tz, args.date, mode["days"], mode["top"],
221
+ want_tides=want_tides, want_weather=want_weather,
222
+ console=console)
223
+ return 0
224
+
225
+
226
+ def _run_panel(loc, tz, start_date, days, *,
227
+ want_tides, want_weather, console):
228
+ targets = [start_date + timedelta(days=i) for i in range(days)]
229
+ trend_dates = [start_date + timedelta(days=i) for i in range(days + 6)]
230
+ trend_scores = [build_day(d, loc["lat"], loc["lon"], loc["tz"])["score"]
231
+ for d in trend_dates]
232
+
233
+ built = _build_days(loc, tz, targets,
234
+ want_tides=want_tides, want_weather=want_weather,
235
+ console=console)
236
+ for i, day in enumerate(built):
237
+ day["trend"] = trend_scores[i:i + 7]
238
+ render_day(day, loc["location"], console=console)
239
+
240
+
241
+ def _run_list(loc, tz, start_date, days, *,
242
+ want_tides, want_weather, console):
243
+ targets = [start_date + timedelta(days=i) for i in range(days)]
244
+ built = _build_days(loc, tz, targets,
245
+ want_tides=want_tides, want_weather=want_weather,
246
+ console=console)
247
+ render_list(built, loc["location"], console=console)
248
+
249
+
250
+ def _run_month(loc, ref_date, *, console):
251
+ year, month = ref_date.year, ref_date.month
252
+ num_days = calendar.monthrange(year, month)[1]
253
+ days = [build_day(date(year, month, d),
254
+ loc["lat"], loc["lon"], loc["tz"])
255
+ for d in range(1, num_days + 1)]
256
+ render_month(days, loc["location"], console=console)
257
+
258
+
259
+ def _run_best(loc, tz, start_date, days, top, *,
260
+ want_tides, want_weather, console):
261
+ targets = [start_date + timedelta(days=i) for i in range(days)]
262
+ built = _build_days(loc, tz, targets,
263
+ want_tides=want_tides, want_weather=want_weather,
264
+ console=console)
265
+ render_best(built, loc["location"], top_n=top, console=console)
266
+
267
+
268
+ def cli_main() -> None:
269
+ """Console-script entry point (installed by pyproject)."""
270
+ raise SystemExit(main())
271
+
272
+
273
+ if __name__ == "__main__":
274
+ cli_main()
fishin/config.py ADDED
@@ -0,0 +1,46 @@
1
+ """Read/write `~/.config/fishin/config.toml`.
2
+
3
+ The file is intentionally flat — a handful of top-level keys, no sections. We
4
+ read with stdlib `tomllib` (3.11+) and write by hand to avoid pulling in
5
+ `tomli-w` for five lines of output.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import tomllib
12
+ from pathlib import Path
13
+
14
+
15
+ _VALID_KEYS = {"location", "lat", "lon", "tz", "station"}
16
+
17
+
18
+ def config_path() -> Path:
19
+ base = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
20
+ return base / "fishin" / "config.toml"
21
+
22
+
23
+ def load_config(path: Path | None = None) -> dict:
24
+ path = path or config_path()
25
+ if not path.exists():
26
+ return {}
27
+ with path.open("rb") as f:
28
+ data = tomllib.load(f)
29
+ return {k: v for k, v in data.items() if k in _VALID_KEYS}
30
+
31
+
32
+ def save_config(values: dict, path: Path | None = None) -> Path:
33
+ path = path or config_path()
34
+ path.parent.mkdir(parents=True, exist_ok=True)
35
+ lines: list[str] = []
36
+ for key in ("location", "lat", "lon", "tz", "station"):
37
+ if key not in values or values[key] is None:
38
+ continue
39
+ v = values[key]
40
+ if isinstance(v, (int, float)):
41
+ lines.append(f"{key} = {v}")
42
+ else:
43
+ escaped = str(v).replace("\\", "\\\\").replace('"', '\\"')
44
+ lines.append(f'{key} = "{escaped}"')
45
+ path.write_text("\n".join(lines) + "\n")
46
+ return path