aboutsummaryrefslogtreecommitdiffstats
path: root/config/hypr/UserScripts/Weather.py
blob: a71fe8caa40ce6855eba5539151b39f8889f96dd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
#!/usr/bin/env python3
# /* ---- šŸ’« https://github.com/JaKooLit šŸ’« ---- */  #
# Rewritten to use Open-Meteo APIs (worldwide, no API key) for robust weather data.
# Outputs Waybar-compatible JSON and a simple text cache.

import json
import os
import sys
import time
import html
from typing import Any, Dict, List, Optional, Tuple
from datetime import datetime

import requests

# =============== Configuration ===============
# You can configure behavior via environment variables OR the constants below.
# Examples (zsh):
#   # One-off run
#   # WEATHER_UNITS can be "metric" or "imperial"
#   WEATHER_UNITS=imperial WEATHER_PLACE="Concord, NH" python3 ~/.config/hypr/UserScripts/Weather.py
#
#   # Persist in current shell session
#   export WEATHER_UNITS=imperial
#   export WEATHER_LAT=43.2229
#   export WEATHER_LON=-71.332
#   export WEATHER_PLACE="Concord, NH"
#   export WEATHER_TOOLTIP_MARKUP=1   # 1 to enable Pango markup, 0 to disable
#   export WEATHER_LOC_ICON="šŸ“"      # or "*" for ASCII-only
#
CACHE_DIR = os.path.expanduser("~/.cache")
API_CACHE_PATH = os.path.join(CACHE_DIR, "open_meteo_cache.json")
SIMPLE_TEXT_CACHE_PATH = os.path.join(CACHE_DIR, ".weather_cache")
CACHE_TTL_SECONDS = int(os.getenv("WEATHER_CACHE_TTL", "600"))  # default 10 minutes

# Units: metric or imperial (default metric)
UNITS = os.getenv("WEATHER_UNITS", "metric").strip().lower()  # metric|imperial

# Optional manual coordinates
ENV_LAT = os.getenv("WEATHER_LAT")
ENV_LON = os.getenv("WEATHER_LON")
# Optional manual place override for tooltip
ENV_PLACE = os.getenv("WEATHER_PLACE")
# Manual place name set inside this file. If set (non-empty), this takes top priority.
# Example: MANUAL_PLACE = "Concord, NH, US"
MANUAL_PLACE: Optional[str] = None

# Location icon in tooltip (default to a standard emoji to avoid missing glyphs)
LOC_ICON = os.getenv("WEATHER_LOC_ICON", "šŸ“")
# Enable/disable Pango markup in tooltip (1/0, true/false)
TOOLTIP_MARKUP = os.getenv("WEATHER_TOOLTIP_MARKUP", "1").lower() not in ("0", "false", "no")
# Optional debug logging to stderr (set WEATHER_DEBUG=1 to enable)
DEBUG = os.getenv("WEATHER_DEBUG", "0").lower() not in ("0", "false", "no")

# HTTP settings
UA = (
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/128.0 Safari/537.36"
)
TIMEOUT = 8

SESSION = requests.Session()
SESSION.headers.update({"User-Agent": UA})

# =============== Icon and status mapping ===============
# Reuse prior icon set for continuity
WEATHER_ICONS = {
    "sunnyDay": "󰖙",
    "clearNight": "󰖔",
    "cloudyFoggyDay": "",
    "cloudyFoggyNight": "ī†",
    "rainyDay": "īŒ†",
    "rainyNight": "",
    "snowyIcyDay": "",
    "snowyIcyNight": "",
    "severe": "ī®",
    "default": "īŒ‚",
}

WMO_STATUS = {
    0: "Clear sky",
    1: "Mainly clear",
    2: "Partly cloudy",
    3: "Overcast",
    45: "Fog",
    48: "Depositing rime fog",
    51: "Light drizzle",
    53: "Moderate drizzle",
    55: "Dense drizzle",
    56: "Freezing drizzle",
    57: "Freezing drizzle",
    61: "Light rain",
    63: "Moderate rain",
    65: "Heavy rain",
    66: "Freezing rain",
    67: "Freezing rain",
    71: "Slight snow",
    73: "Moderate snow",
    75: "Heavy snow",
    77: "Snow grains",
    80: "Rain showers",
    81: "Rain showers",
    82: "Violent rain showers",
    85: "Snow showers",
    86: "Heavy snow showers",
    95: "Thunderstorm",
    96: "Thunderstorm w/ hail",
    99: "Thunderstorm w/ hail",
}


def wmo_to_icon(code: int, is_day: int) -> str:
    day = bool(is_day)
    if code == 0:
        return WEATHER_ICONS["sunnyDay" if day else "clearNight"]
    if code in (1, 2, 3, 45, 48):
        return WEATHER_ICONS["cloudyFoggyDay" if day else "cloudyFoggyNight"]
    if code in (51, 53, 55, 61, 63, 65, 80, 81, 82):
        return WEATHER_ICONS["rainyDay" if day else "rainyNight"]
    if code in (56, 57, 66, 67, 71, 73, 75, 77, 85, 86):
        return WEATHER_ICONS["snowyIcyDay" if day else "snowyIcyNight"]
    if code in (95, 96, 99):
        return WEATHER_ICONS["severe"]
    return WEATHER_ICONS["default"]


def wmo_to_status(code: int) -> str:
    return WMO_STATUS.get(code, "Unknown")


# =============== Utilities ===============

def esc(s: Optional[str]) -> str:
    return html.escape(s, quote=False) if s else ""

def log_debug(msg: str) -> None:
    if DEBUG:
        print(msg, file=sys.stderr)

def ensure_cache_dir() -> None:
    try:
        os.makedirs(CACHE_DIR, exist_ok=True)
    except Exception as e:
        print(f"Error creating cache dir: {e}", file=sys.stderr)


def read_api_cache() -> Optional[Dict[str, Any]]:
    try:
        if not os.path.exists(API_CACHE_PATH):
            return None
        with open(API_CACHE_PATH, "r", encoding="utf-8") as f:
            data = json.load(f)
        if (time.time() - data.get("timestamp", 0)) <= CACHE_TTL_SECONDS:
            return data
        return None
    except Exception as e:
        print(f"Error reading cache: {e}", file=sys.stderr)
        return None


def write_api_cache(payload: Dict[str, Any]) -> None:
    try:
        ensure_cache_dir()
        payload["timestamp"] = time.time()
        with open(API_CACHE_PATH, "w", encoding="utf-8") as f:
            json.dump(payload, f)
    except Exception as e:
        print(f"Error writing API cache: {e}", file=sys.stderr)


def write_simple_text_cache(text: str) -> None:
    try:
        ensure_cache_dir()
        with open(SIMPLE_TEXT_CACHE_PATH, "w", encoding="utf-8") as f:
            f.write(text)
    except Exception as e:
        print(f"Error writing simple cache: {e}", file=sys.stderr)


def get_coords() -> Tuple[float, float]:
    # 1) Explicit env
    if ENV_LAT and ENV_LON:
        try:
            return float(ENV_LAT), float(ENV_LON)
        except ValueError:
            print("Invalid WEATHER_LAT/WEATHER_LON; falling back to IP geolocation", file=sys.stderr)

    # 2) Try cached coordinates from last successful forecast
    try:
        cached = read_api_cache()
        if cached and isinstance(cached, dict):
            fc = cached.get("forecast") or {}
            lat = fc.get("latitude")
            lon = fc.get("longitude")
            if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
                return float(lat), float(lon)
    except Exception as e:
        print(f"Reading cached coords failed: {e}", file=sys.stderr)

    # 3) IP-based geolocation with multiple providers (prefer ipwho.is, ipapi.co; ipinfo.io as fallback)
    # ipwho.is
    try:
        resp = SESSION.get("https://ipwho.is/", timeout=TIMEOUT)
        resp.raise_for_status()
        data = resp.json()
        if data.get("success"):
            lat = data.get("latitude")
            lon = data.get("longitude")
            if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
                return float(lat), float(lon)
    except Exception as e:
        print(f"ipwho.is failed: {e}", file=sys.stderr)

    # ipapi.co
    try:
        resp = SESSION.get("https://ipapi.co/json", timeout=TIMEOUT)
        resp.raise_for_status()
        data = resp.json()
        lat = data.get("latitude")
        lon = data.get("longitude")
        if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
            return float(lat), float(lon)
    except Exception as e:
        print(f"ipapi.co failed: {e}", file=sys.stderr)

    # ipinfo.io (fallback)
    try:
        resp = SESSION.get("https://ipinfo.io/json", timeout=TIMEOUT)
        resp.raise_for_status()
        data = resp.json()
        loc = data.get("loc")
        if loc and "," in loc:
            lat_s, lon_s = loc.split(",", 1)
            return float(lat_s), float(lon_s)
    except Exception as e:
        print(f"ipinfo.io failed: {e}", file=sys.stderr)

    # 4) Last resort
    print("IP geolocation failed: no providers succeeded", file=sys.stderr)
    return 0.0, 0.0


def units_params(units: str) -> Dict[str, str]:
    if units == "imperial":
        return {
            "temperature_unit": "fahrenheit",
            "wind_speed_unit": "mph",
            "precipitation_unit": "inch",
        }
    # default metric
    return {
        "temperature_unit": "celsius",
        "wind_speed_unit": "kmh",
        "precipitation_unit": "mm",
    }


def format_visibility(meters: Optional[float]) -> str:
    if meters is None:
        return ""
    try:
        if UNITS == "imperial":
            miles = meters / 1609.344
            return f"{miles:.1f} mi"
        else:
            km = meters / 1000.0
            return f"{km:.1f} km"
    except Exception:
        return ""


# =============== API Fetching ===============

def fetch_open_meteo(lat: float, lon: float) -> Dict[str, Any]:
    base = "https://api.open-meteo.com/v1/forecast"
    params = {
        "latitude": lat,
        "longitude": lon,
        "current": "temperature_2m,apparent_temperature,relative_humidity_2m,wind_speed_10m,wind_direction_10m,weather_code,visibility,precipitation,pressure_msl,is_day",
        "hourly": "precipitation_probability,weather_code",
        "daily": "temperature_2m_max,temperature_2m_min",
        "timezone": "auto",
    }
    params.update(units_params(UNITS))
    resp = SESSION.get(base, params=params, timeout=TIMEOUT)
    resp.raise_for_status()
    return resp.json()


def fetch_aqi(lat: float, lon: float) -> Optional[Dict[str, Any]]:
    try:
        base = "https://air-quality-api.open-meteo.com/v1/air-quality"
        params = {
            "latitude": lat,
            "longitude": lon,
            "current": "european_aqi",
            "timezone": "auto",
        }
        resp = SESSION.get(base, params=params, timeout=TIMEOUT)
        resp.raise_for_status()
        return resp.json()
    except Exception as e:
        print(f"AQI fetch failed: {e}", file=sys.stderr)
        return None


def fetch_place(lat: float, lon: float) -> Optional[str]:
    """Reverse geocode lat/lon to an approximate place. Tries Nominatim first, then Open-Meteo."""
    lang = os.getenv("WEATHER_LANG", "en")

    # 1) Nominatim (OpenStreetMap)
    try:
        base = "https://nominatim.openstreetmap.org/reverse"
        params = {
            "lat": lat,
            "lon": lon,
            "format": "jsonv2",
            "accept-language": lang,
        }
        headers = {"User-Agent": UA + " Weather.py/1.0"}
        resp = SESSION.get(base, params=params, headers=headers, timeout=TIMEOUT)
        resp.raise_for_status()
        data = resp.json()
        address = data.get("address", {})
        name = data.get("name") or address.get("city") or address.get("town") or address.get("village") or address.get("hamlet")
        admin1 = address.get("state")
        country = address.get("country")
        parts = [part for part in [name, admin1, country] if part]
        if parts:
            return ", ".join(parts)
    except Exception as e:
        log_debug(f"Reverse geocoding (Nominatim) failed: {e}")

    # 2) Open-Meteo reverse (fallback)
    try:
        base = "https://geocoding-api.open-meteo.com/v1/reverse"
        params = {
            "latitude": lat,
            "longitude": lon,
            "language": lang,
            "format": "json",
        }
        resp = SESSION.get(base, params=params, timeout=TIMEOUT)
        resp.raise_for_status()
        data = resp.json()
        results = data.get("results") or []
        if results:
            p = results[0]
            name = p.get("name")
            admin1 = p.get("admin1")
            country = p.get("country")
            parts = [part for part in [name, admin1, country] if part]
            if parts:
                return ", ".join(parts)
    except Exception as e:
        log_debug(f"Reverse geocoding (Open-Meteo) failed: {e}")

    return None


# =============== Build Output ===============

def safe_get(dct: Dict[str, Any], *keys, default=None):
    cur: Any = dct
    for k in keys:
        if isinstance(cur, dict):
            if k not in cur:
                return default
            cur = cur[k]
        elif isinstance(cur, list):
            try:
                cur = cur[k]  # type: ignore[index]
            except Exception:
                return default
        else:
            return default
    return cur


def build_hourly_precip(forecast: Dict[str, Any]) -> str:
    try:
        times: List[str] = safe_get(forecast, "hourly", "time", default=[]) or []
        probs: List[Optional[float]] = safe_get(
            forecast, "hourly", "precipitation_probability", default=[]
        ) or []
        cur_time: Optional[str] = safe_get(forecast, "current", "time")
        idx = times.index(cur_time) if cur_time in times else 0
        window = probs[idx : idx + 6]
        if not window:
            return ""
        parts = [f"{int(p)}%" if p is not None else "-" for p in window]
        return " (next 6h) " + " ".join(parts)
    except Exception:
        return ""


def build_output(lat: float, lon: float, forecast: Dict[str, Any], aqi: Optional[Dict[str, Any]], place: Optional[str] = None) -> Tuple[Dict[str, Any], str]:
    cur = forecast.get("current", {})
    cur_units = forecast.get("current_units", {})
    daily = forecast.get("daily", {})
    daily_units = forecast.get("daily_units", {})

    temp_val = cur.get("temperature_2m")
    temp_unit = cur_units.get("temperature_2m", "")
    temp_str = f"{int(round(temp_val))}{temp_unit}" if isinstance(temp_val, (int, float)) else "N/A"

    feels_val = cur.get("apparent_temperature")
    feels_unit = cur_units.get("apparent_temperature", "")
    feels_str = f"Feels like {int(round(feels_val))}{feels_unit}" if isinstance(feels_val, (int, float)) else ""

    is_day = int(cur.get("is_day", 1) or 1)
    code = int(cur.get("weather_code", -1) or -1)

    unavailable = False
    if code == -1:
        try:
            times: List[str] = safe_get(forecast, "hourly", "time", default=[]) or []
            codes: List[Optional[int]] = safe_get(forecast, "hourly", "weather_code", default=[]) or []
            cur_time: Optional[str] = safe_get(forecast, "current", "time")

            idx = 0
            if cur_time and times:
                try:
                    ct = datetime.fromisoformat(cur_time)
                    diffs = []
                    for t in times:
                        try:
                            diffs.append(abs((datetime.fromisoformat(t) - ct).total_seconds()))
                        except Exception:
                            diffs.append(float("inf"))
                    idx = min(range(len(diffs)), key=lambda i: diffs[i]) if diffs else 0
                except Exception:
                    idx = times.index(cur_time) if cur_time in times else 0

            hcode = None
            if isinstance(codes, list) and codes:
                if idx < len(codes) and isinstance(codes[idx], (int, float)):
                    hcode = int(codes[idx])
                else:
                    for c in codes:
                        if isinstance(c, (int, float)):
                            hcode = int(c)
                            break
            if isinstance(hcode, int):
                code = hcode
                log_debug(f"Fallback hourly weather_code used: code={code} idx={idx} cur_time={cur_time}")
        except Exception as e:
            log_debug(f"Hourly code fallback failed: {e}")

    if not isinstance(code, int) or code < 0:
        unavailable = True
        log_debug("Weather code invalid; setting status to 'Condition Unavailable'")

    if unavailable:
        icon = WEATHER_ICONS["default"]
        status = "Condition Unavailable"
        code_for_class = "unavailable"
    else:
        icon = wmo_to_icon(code, is_day)
        status = wmo_to_status(code)
        code_for_class = f"wmo-{code} {'day' if is_day else 'night'}"

    # min/max today (index 0)
    tmin_val = safe_get(daily, "temperature_2m_min", 0)
    tmax_val = safe_get(daily, "temperature_2m_max", 0)
    dtemp_unit = daily_units.get("temperature_2m_min", temp_unit)
    tmin_str = f"{int(round(tmin_val))}{dtemp_unit}" if isinstance(tmin_val, (int, float)) else ""
    tmax_str = f"{int(round(tmax_val))}{dtemp_unit}" if isinstance(tmax_val, (int, float)) else ""
    min_max = f"ļ‹‹  {tmin_str}\t\t  {tmax_str}" if tmin_str and tmax_str else ""

    wind_val = cur.get("wind_speed_10m")
    wind_unit = cur_units.get("wind_speed_10m", "")
    wind_text = f"  {int(round(wind_val))}{wind_unit}" if isinstance(wind_val, (int, float)) else ""

    hum_val = cur.get("relative_humidity_2m")
    humidity_text = f"ī³  {int(hum_val)}%" if isinstance(hum_val, (int, float)) else ""

    vis_val = cur.get("visibility")
    visibility_text = f"  {format_visibility(vis_val)}" if isinstance(vis_val, (int, float)) else ""

    aqi_val = safe_get(aqi or {}, "current", "european_aqi")
    aqi_text = f"AQI {int(aqi_val)}" if isinstance(aqi_val, (int, float)) else "AQI N/A"

    hourly_precip = build_hourly_precip(forecast)
    prediction = f"\n\n{hourly_precip}" if hourly_precip else ""

    # Build place string (priority: MANUAL_PLACE > ENV_PLACE > reverse geocode > lat,lon)
    place_str = (MANUAL_PLACE or ENV_PLACE or place or f"{lat:.3f}, {lon:.3f}")
    location_text = f"{LOC_ICON}  {place_str}"

    # Build tooltip (markup or plain)
    if TOOLTIP_MARKUP:
        # Escape dynamic text to avoid breaking Pango markup
        tooltip_text = str.format(
            "\t\t{}\t\t\n{}\n{}\n{}\n{}\n\n{}\n{}\n{}{}",
            f'<span size="xx-large">{esc(temp_str)}</span>',
            f"<big> {icon}</big>",
            f"<b>{esc(status)}</b>",
            esc(location_text),
            f"<small>{esc(feels_str)}</small>" if feels_str else "",
            f"<b>{esc(min_max)}</b>" if min_max else "",
            f"{esc(wind_text)}\t{esc(humidity_text)}",
            f"{esc(visibility_text)}\t{esc(aqi_text)}",
            f"<i> {esc(prediction)}</i>" if prediction else "",
        )
    else:
        lines = [
            f"{icon}  {temp_str}",
            status,
            location_text,
        ]
        if feels_str:
            lines.append(feels_str)
        if min_max:
            lines.append(min_max)
        lines.append(f"{wind_text} {humidity_text}".strip())
        lines.append(f"{visibility_text} {aqi_text}".strip())
        if prediction:
            lines.append(hourly_precip)
        tooltip_text = "\n".join([ln for ln in lines if ln])

    out_data = {
        "text": f"{icon}  {temp_str}",
        "alt": status,
        "tooltip": tooltip_text,
        "class": code_for_class,
    }

    simple_weather = (
        f"{icon}  {status}\n"
        + f"  {temp_str} ({feels_str})\n"
        + (f"{wind_text} \n" if wind_text else "")
        + (f"{humidity_text} \n" if humidity_text else "")
        + f"{visibility_text} {aqi_text}\n"
    )

    return out_data, simple_weather


def main() -> None:
    lat, lon = get_coords()

    # Try cache first
    cached = read_api_cache()
    if cached and isinstance(cached, dict):
        forecast = cached.get("forecast")
        aqi = cached.get("aqi")
        cached_place = cached.get("place") if isinstance(cached.get("place"), str) else None
        place_effective = MANUAL_PLACE or ENV_PLACE or cached_place
        try:
            out, simple = build_output(lat, lon, forecast, aqi, place_effective)
            print(json.dumps(out, ensure_ascii=False))
            write_simple_text_cache(simple)
            return
        except Exception as e:
            print(f"Cached data build failed, refetching: {e}", file=sys.stderr)

    # Fetch fresh
    try:
        forecast = fetch_open_meteo(lat, lon)
        aqi = fetch_aqi(lat, lon)
        # Use manual/env place if provided; otherwise reverse geocode
        place_effective = MANUAL_PLACE or ENV_PLACE or fetch_place(lat, lon)
        write_api_cache({"forecast": forecast, "aqi": aqi, "place": place_effective})
        out, simple = build_output(lat, lon, forecast, aqi, place_effective)
        print(json.dumps(out, ensure_ascii=False))
        write_simple_text_cache(simple)
    except Exception as e:
        print(f"Open-Meteo fetch failed: {e}", file=sys.stderr)
        # Last resort: try stale cache without TTL
        try:
            if os.path.exists(API_CACHE_PATH):
                with open(API_CACHE_PATH, "r", encoding="utf-8") as f:
                    stale = json.load(f)
                out, simple = build_output(lat, lon, stale.get("forecast", {}), stale.get("aqi"), stale.get("place") if isinstance(stale.get("place"), str) else None)
                print(json.dumps(out, ensure_ascii=False))
                write_simple_text_cache(simple)
                return
        except Exception as e2:
            print(f"Failed to use stale cache: {e2}", file=sys.stderr)
        # Fallback minimal output
        fallback = {
            "text": f"{WEATHER_ICONS['default']}  N/A",
            "alt": "Unavailable",
            "tooltip": "Weather unavailable",
            "class": "unavailable",
        }
        print(json.dumps(fallback, ensure_ascii=False))


if __name__ == "__main__":
    main()
status = html_data("div[data-testid='wxPhrase']").text()
status = f"{status[:16]}.." if len(status) > 17 else status

# status code
status_code = html_data("#regionHeader").attr("class").split(" ")[2].split("-")[2]

# status icon
icon = (
    weather_icons[status_code]
    if status_code in weather_icons
    else weather_icons["default"]
)

# temperature feels like
temp_feel = html_data(
    "div[data-testid='FeelsLikeSection'] > span > span[data-testid='TemperatureValue']"
).text()
temp_feel_text = f"Feels like {temp_feel}c"

# min-max temperature
temp_min = (
    html_data("div[data-testid='wxData'] > span[data-testid='TemperatureValue']")
    .eq(1)
    .text()
)
temp_max = (
    html_data("div[data-testid='wxData'] > span[data-testid='TemperatureValue']")
    .eq(0)
    .text()
)
temp_min_max = f"ļ‹‹  {temp_min}\t\t  {temp_max}"

# wind speed
wind_speed = html_data("span[data-testid='Wind']").text().split("\n")[1]
wind_text = f"  {wind_speed}"

# humidity
humidity = html_data("span[data-testid='PercentageValue']").text()
humidity_text = f"ī³  {humidity}"

# visibility
visibility = html_data("span[data-testid='VisibilityValue']").text()
visibility_text = f"  {visibility}"

# air quality index
air_quality_index = html_data("text[data-testid='DonutChartValue']").text()

# hourly rain prediction
prediction = html_data("section[aria-label='Hourly Forecast']")(
    "div[data-testid='SegmentPrecipPercentage'] > span"
).text()
prediction = prediction.replace("Chance of Rain", "")
prediction = f"\n\n (hourly) {prediction}" if len(prediction) > 0 else prediction

# tooltip text
tooltip_text = str.format(
    "\t\t{}\t\t\n{}\n{}\n{}\n\n{}\n{}\n{}{}",
    f'<span size="xx-large">{temp}</span>',
    f"<big> {icon}</big>",
    f"<b>{status}</b>",
    f"<small>{temp_feel_text}</small>",
    f"<b>{temp_min_max}</b>",
    f"{wind_text}\t{humidity_text}",
    f"{visibility_text}\tAQI {air_quality_index}",
    f"<i> {prediction}</i>",
)

# print waybar module data
out_data = {
    "text": f"{icon}  {temp}",
    "alt": status,
    "tooltip": tooltip_text,
    "class": status_code,
=======
WMO_STATUS = {
    0: "Clear sky",
    1: "Mainly clear",
    2: "Partly cloudy",
    3: "Overcast",
    45: "Fog",
    48: "Depositing rime fog",
    51: "Light drizzle",
    53: "Moderate drizzle",
    55: "Dense drizzle",
    56: "Freezing drizzle",
    57: "Freezing drizzle",
    61: "Light rain",
    63: "Moderate rain",
    65: "Heavy rain",
    66: "Freezing rain",
    67: "Freezing rain",
    71: "Slight snow",
    73: "Moderate snow",
    75: "Heavy snow",
    77: "Snow grains",
    80: "Rain showers",
    81: "Rain showers",
    82: "Violent rain showers",
    85: "Snow showers",
    86: "Heavy snow showers",
    95: "Thunderstorm",
    96: "Thunderstorm w/ hail",
    99: "Thunderstorm w/ hail",
>>>>>>> 2a5a7c5 (Weather.py: switch to Open-Meteo; add caching, reverse geocoding, robust geolocation, and config options)
}


def wmo_to_icon(code: int, is_day: int) -> str:
    day = bool(is_day)
    if code == 0:
        return WEATHER_ICONS["sunnyDay" if day else "clearNight"]
    if code in (1, 2, 3, 45, 48):
        return WEATHER_ICONS["cloudyFoggyDay" if day else "cloudyFoggyNight"]
    if code in (51, 53, 55, 61, 63, 65, 80, 81, 82):
        return WEATHER_ICONS["rainyDay" if day else "rainyNight"]
    if code in (56, 57, 66, 67, 71, 73, 75, 77, 85, 86):
        return WEATHER_ICONS["snowyIcyDay" if day else "snowyIcyNight"]
    if code in (95, 96, 99):
        return WEATHER_ICONS["severe"]
    return WEATHER_ICONS["default"]


def wmo_to_status(code: int) -> str:
    return WMO_STATUS.get(code, "Unknown")


# =============== Utilities ===============

def esc(s: Optional[str]) -> str:
    return html.escape(s, quote=False) if s else ""

def log_debug(msg: str) -> None:
    if DEBUG:
        print(msg, file=sys.stderr)

def ensure_cache_dir() -> None:
    try:
        os.makedirs(CACHE_DIR, exist_ok=True)
    except Exception as e:
        print(f"Error creating cache dir: {e}", file=sys.stderr)


def read_api_cache() -> Optional[Dict[str, Any]]:
    try:
        if not os.path.exists(API_CACHE_PATH):
            return None
        with open(API_CACHE_PATH, "r", encoding="utf-8") as f:
            data = json.load(f)
        if (time.time() - data.get("timestamp", 0)) <= CACHE_TTL_SECONDS:
            return data
        return None
    except Exception as e:
        print(f"Error reading cache: {e}", file=sys.stderr)
        return None


def write_api_cache(payload: Dict[str, Any]) -> None:
    try:
        ensure_cache_dir()
        payload["timestamp"] = time.time()
        with open(API_CACHE_PATH, "w", encoding="utf-8") as f:
            json.dump(payload, f)
    except Exception as e:
        print(f"Error writing API cache: {e}", file=sys.stderr)


def write_simple_text_cache(text: str) -> None:
    try:
        ensure_cache_dir()
        with open(SIMPLE_TEXT_CACHE_PATH, "w", encoding="utf-8") as f:
            f.write(text)
    except Exception as e:
        print(f"Error writing simple cache: {e}", file=sys.stderr)


def get_coords() -> Tuple[float, float]:
    # 1) Explicit env
    if ENV_LAT and ENV_LON:
        try:
            return float(ENV_LAT), float(ENV_LON)
        except ValueError:
            print("Invalid WEATHER_LAT/WEATHER_LON; falling back to IP geolocation", file=sys.stderr)

    # 2) Try cached coordinates from last successful forecast
    try:
        cached = read_api_cache()
        if cached and isinstance(cached, dict):
            fc = cached.get("forecast") or {}
            lat = fc.get("latitude")
            lon = fc.get("longitude")
            if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
                return float(lat), float(lon)
    except Exception as e:
        print(f"Reading cached coords failed: {e}", file=sys.stderr)

    # 3) IP-based geolocation with multiple providers (prefer ipwho.is, ipapi.co; ipinfo.io as fallback)
    # ipwho.is
    try:
        resp = SESSION.get("https://ipwho.is/", timeout=TIMEOUT)
        resp.raise_for_status()
        data = resp.json()
        if data.get("success"):
            lat = data.get("latitude")
            lon = data.get("longitude")
            if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
                return float(lat), float(lon)
    except Exception as e:
        print(f"ipwho.is failed: {e}", file=sys.stderr)

    # ipapi.co
    try:
        resp = SESSION.get("https://ipapi.co/json", timeout=TIMEOUT)
        resp.raise_for_status()
        data = resp.json()
        lat = data.get("latitude")
        lon = data.get("longitude")
        if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
            return float(lat), float(lon)
    except Exception as e:
        print(f"ipapi.co failed: {e}", file=sys.stderr)

    # ipinfo.io (fallback)
    try:
        resp = SESSION.get("https://ipinfo.io/json", timeout=TIMEOUT)
        resp.raise_for_status()
        data = resp.json()
        loc = data.get("loc")
        if loc and "," in loc:
            lat_s, lon_s = loc.split(",", 1)
            return float(lat_s), float(lon_s)
    except Exception as e:
        print(f"ipinfo.io failed: {e}", file=sys.stderr)

    # 4) Last resort
    print("IP geolocation failed: no providers succeeded", file=sys.stderr)
    return 0.0, 0.0


def units_params(units: str) -> Dict[str, str]:
    if units == "imperial":
        return {
            "temperature_unit": "fahrenheit",
            "wind_speed_unit": "mph",
            "precipitation_unit": "inch",
        }
    # default metric
    return {
        "temperature_unit": "celsius",
        "wind_speed_unit": "kmh",
        "precipitation_unit": "mm",
    }


def format_visibility(meters: Optional[float]) -> str:
    if meters is None:
        return ""
    try:
        if UNITS == "imperial":
            miles = meters / 1609.344
            return f"{miles:.1f} mi"
        else:
            km = meters / 1000.0
            return f"{km:.1f} km"
    except Exception:
        return ""


# =============== API Fetching ===============

def fetch_open_meteo(lat: float, lon: float) -> Dict[str, Any]:
    base = "https://api.open-meteo.com/v1/forecast"
    params = {
        "latitude": lat,
        "longitude": lon,
        "current": "temperature_2m,apparent_temperature,relative_humidity_2m,wind_speed_10m,wind_direction_10m,weather_code,visibility,precipitation,pressure_msl,is_day",
        "hourly": "precipitation_probability",
        "daily": "temperature_2m_max,temperature_2m_min",
        "timezone": "auto",
    }
    params.update(units_params(UNITS))
    resp = SESSION.get(base, params=params, timeout=TIMEOUT)
    resp.raise_for_status()
    return resp.json()


def fetch_aqi(lat: float, lon: float) -> Optional[Dict[str, Any]]:
    try:
        base = "https://air-quality-api.open-meteo.com/v1/air-quality"
        params = {
            "latitude": lat,
            "longitude": lon,
            "current": "european_aqi",
            "timezone": "auto",
        }
        resp = SESSION.get(base, params=params, timeout=TIMEOUT)
        resp.raise_for_status()
        return resp.json()
    except Exception as e:
        print(f"AQI fetch failed: {e}", file=sys.stderr)
        return None


def fetch_place(lat: float, lon: float) -> Optional[str]:
    """Reverse geocode lat/lon to an approximate place. Tries Nominatim first, then Open-Meteo."""
    lang = os.getenv("WEATHER_LANG", "en")

    # 1) Nominatim (OpenStreetMap)
    try:
        base = "https://nominatim.openstreetmap.org/reverse"
        params = {
            "lat": lat,
            "lon": lon,
            "format": "jsonv2",
            "accept-language": lang,
        }
        headers = {"User-Agent": UA + " Weather.py/1.0"}
        resp = SESSION.get(base, params=params, headers=headers, timeout=TIMEOUT)
        resp.raise_for_status()
        data = resp.json()
        address = data.get("address", {})
        name = data.get("name") or address.get("city") or address.get("town") or address.get("village") or address.get("hamlet")
        admin1 = address.get("state")
        country = address.get("country")
        parts = [part for part in [name, admin1, country] if part]
        if parts:
            return ", ".join(parts)
    except Exception as e:
        log_debug(f"Reverse geocoding (Nominatim) failed: {e}")

    # 2) Open-Meteo reverse (fallback)
    try:
        base = "https://geocoding-api.open-meteo.com/v1/reverse"
        params = {
            "latitude": lat,
            "longitude": lon,
            "language": lang,
            "format": "json",
        }
        resp = SESSION.get(base, params=params, timeout=TIMEOUT)
        resp.raise_for_status()
        data = resp.json()
        results = data.get("results") or []
        if results:
            p = results[0]
            name = p.get("name")
            admin1 = p.get("admin1")
            country = p.get("country")
            parts = [part for part in [name, admin1, country] if part]
            if parts:
                return ", ".join(parts)
    except Exception as e:
        log_debug(f"Reverse geocoding (Open-Meteo) failed: {e}")

    return None


# =============== Build Output ===============

def safe_get(dct: Dict[str, Any], *keys, default=None):
    cur: Any = dct
    for k in keys:
        if isinstance(cur, dict):
            if k not in cur:
                return default
            cur = cur[k]
        elif isinstance(cur, list):
            try:
                cur = cur[k]  # type: ignore[index]
            except Exception:
                return default
        else:
            return default
    return cur


def build_hourly_precip(forecast: Dict[str, Any]) -> str:
    try:
        times: List[str] = safe_get(forecast, "hourly", "time", default=[]) or []
        probs: List[Optional[float]] = safe_get(
            forecast, "hourly", "precipitation_probability", default=[]
        ) or []
        cur_time: Optional[str] = safe_get(forecast, "current", "time")
        idx = times.index(cur_time) if cur_time in times else 0
        window = probs[idx : idx + 6]
        if not window:
            return ""
        parts = [f"{int(p)}%" if p is not None else "-" for p in window]
        return " (next 6h) " + " ".join(parts)
    except Exception:
        return ""


def build_output(lat: float, lon: float, forecast: Dict[str, Any], aqi: Optional[Dict[str, Any]], place: Optional[str] = None) -> Tuple[Dict[str, Any], str]:
    cur = forecast.get("current", {})
    cur_units = forecast.get("current_units", {})
    daily = forecast.get("daily", {})
    daily_units = forecast.get("daily_units", {})

    temp_val = cur.get("temperature_2m")
    temp_unit = cur_units.get("temperature_2m", "")
    temp_str = f"{int(round(temp_val))}{temp_unit}" if isinstance(temp_val, (int, float)) else "N/A"

    feels_val = cur.get("apparent_temperature")
    feels_unit = cur_units.get("apparent_temperature", "")
    feels_str = f"Feels like {int(round(feels_val))}{feels_unit}" if isinstance(feels_val, (int, float)) else ""

    is_day = int(cur.get("is_day", 1) or 1)
    code = int(cur.get("weather_code", -1) or -1)
    icon = wmo_to_icon(code, is_day)
    status = wmo_to_status(code)

    # min/max today (index 0)
    tmin_val = safe_get(daily, "temperature_2m_min", 0)
    tmax_val = safe_get(daily, "temperature_2m_max", 0)
    dtemp_unit = daily_units.get("temperature_2m_min", temp_unit)
    tmin_str = f"{int(round(tmin_val))}{dtemp_unit}" if isinstance(tmin_val, (int, float)) else ""
    tmax_str = f"{int(round(tmax_val))}{dtemp_unit}" if isinstance(tmax_val, (int, float)) else ""
    min_max = f"ļ‹‹  {tmin_str}\t\t  {tmax_str}" if tmin_str and tmax_str else ""

    wind_val = cur.get("wind_speed_10m")
    wind_unit = cur_units.get("wind_speed_10m", "")
    wind_text = f"  {int(round(wind_val))}{wind_unit}" if isinstance(wind_val, (int, float)) else ""

    hum_val = cur.get("relative_humidity_2m")
    humidity_text = f"ī³  {int(hum_val)}%" if isinstance(hum_val, (int, float)) else ""

    vis_val = cur.get("visibility")
    visibility_text = f"  {format_visibility(vis_val)}" if isinstance(vis_val, (int, float)) else ""

    aqi_val = safe_get(aqi or {}, "current", "european_aqi")
    aqi_text = f"AQI {int(aqi_val)}" if isinstance(aqi_val, (int, float)) else "AQI N/A"

    hourly_precip = build_hourly_precip(forecast)
    prediction = f"\n\n{hourly_precip}" if hourly_precip else ""

    # Build place string (priority: MANUAL_PLACE > ENV_PLACE > reverse geocode > lat,lon)
    place_str = (MANUAL_PLACE or ENV_PLACE or place or f"{lat:.3f}, {lon:.3f}")
    location_text = f"{LOC_ICON}  {place_str}"

    # Build tooltip (markup or plain)
    if TOOLTIP_MARKUP:
        # Escape dynamic text to avoid breaking Pango markup
        tooltip_text = str.format(
            "\t\t{}\t\t\n{}\n{}\n{}\n{}\n\n{}\n{}\n{}{}",
            f'<span size="xx-large">{esc(temp_str)}</span>',
            f"<big> {icon}</big>",
            f"<b>{esc(status)}</b>",
            esc(location_text),
            f"<small>{esc(feels_str)}</small>" if feels_str else "",
            f"<b>{esc(min_max)}</b>" if min_max else "",
            f"{esc(wind_text)}\t{esc(humidity_text)}",
            f"{esc(visibility_text)}\t{esc(aqi_text)}",
            f"<i> {esc(prediction)}</i>" if prediction else "",
        )
    else:
        lines = [
            f"{icon}  {temp_str}",
            status,
            location_text,
        ]
        if feels_str:
            lines.append(feels_str)
        if min_max:
            lines.append(min_max)
        lines.append(f"{wind_text} {humidity_text}".strip())
        lines.append(f"{visibility_text} {aqi_text}".strip())
        if prediction:
            lines.append(hourly_precip)
        tooltip_text = "\n".join([ln for ln in lines if ln])

    out_data = {
        "text": f"{icon}  {temp_str}",
        "alt": status,
        "tooltip": tooltip_text,
        "class": f"wmo-{code} {'day' if is_day else 'night'}",
    }

    simple_weather = (
        f"{icon}  {status}\n"
        + f"  {temp_str} ({feels_str})\n"
        + (f"{wind_text} \n" if wind_text else "")
        + (f"{humidity_text} \n" if humidity_text else "")
        + f"{visibility_text} {aqi_text}\n"
    )

    return out_data, simple_weather


def main() -> None:
    lat, lon = get_coords()

    # Try cache first
    cached = read_api_cache()
    if cached and isinstance(cached, dict):
        forecast = cached.get("forecast")
        aqi = cached.get("aqi")
        cached_place = cached.get("place") if isinstance(cached.get("place"), str) else None
        place_effective = MANUAL_PLACE or ENV_PLACE or cached_place
        try:
            out, simple = build_output(lat, lon, forecast, aqi, place_effective)
            print(json.dumps(out, ensure_ascii=False))
            write_simple_text_cache(simple)
            return
        except Exception as e:
            print(f"Cached data build failed, refetching: {e}", file=sys.stderr)

    # Fetch fresh
    try:
        forecast = fetch_open_meteo(lat, lon)
        aqi = fetch_aqi(lat, lon)
        # Use manual/env place if provided; otherwise reverse geocode
        place_effective = MANUAL_PLACE or ENV_PLACE or fetch_place(lat, lon)
        write_api_cache({"forecast": forecast, "aqi": aqi, "place": place_effective})
        out, simple = build_output(lat, lon, forecast, aqi, place_effective)
        print(json.dumps(out, ensure_ascii=False))
        write_simple_text_cache(simple)
    except Exception as e:
        print(f"Open-Meteo fetch failed: {e}", file=sys.stderr)
        # Last resort: try stale cache without TTL
        try:
            if os.path.exists(API_CACHE_PATH):
                with open(API_CACHE_PATH, "r", encoding="utf-8") as f:
                    stale = json.load(f)
                out, simple = build_output(lat, lon, stale.get("forecast", {}), stale.get("aqi"), stale.get("place") if isinstance(stale.get("place"), str) else None)
                print(json.dumps(out, ensure_ascii=False))
                write_simple_text_cache(simple)
                return
        except Exception as e2:
            print(f"Failed to use stale cache: {e2}", file=sys.stderr)
        # Fallback minimal output
        fallback = {
            "text": f"{WEATHER_ICONS['default']}  N/A",
            "alt": "Unavailable",
            "tooltip": "Weather unavailable",
            "class": "unavailable",
        }
        print(json.dumps(fallback, ensure_ascii=False))


if __name__ == "__main__":
    main()
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage