summaryrefslogtreecommitdiff
path: root/wttrin.el
blob: 85eb5c3c88827e947ccb5bc07343ad93576e7ec8 (plain)
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
;;; wttrin.el --- Emacs Frontend for Service wttr.in -*- lexical-binding: t; coding: utf-8; -*-
;;
;; Copyright (C) 2024 Craig Jennings
;; Maintainer: Craig Jennings <c@cjennings.net>
;;
;; Original Authors: Carl X. Su <bcbcarl@gmail.com>
;;                   ono hiroko (kuanyui) <azazabc123@gmail.com>
;; Version: 0.2.3
;; Package-Requires: ((emacs "24.4") (xterm-color "1.0"))
;; Keywords: weather, wttrin, games
;; URL: https://github.com/cjennings/emacs-wttrin

;; SPDX-License-Identifier: GPL-3.0-or-later

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;; This file is NOT part of GNU Emacs.

;;; Commentary:
;; Displays the weather information from the wttr.in service for your submitted
;; location.

;;; Code:

(require 'face-remap)
(require 'url)

;; Declare xterm-color functions (loaded on-demand)
(declare-function xterm-color-filter "xterm-color" (string))

;; Declare functions from wttrin-debug.el (loaded conditionally)
(declare-function wttrin--debug-mode-line-info "wttrin-debug")
(declare-function wttrin--debug-log "wttrin-debug")

(defgroup wttrin nil
  "Emacs frontend for the weather web service wttr.in."
  :prefix "wttrin-"
  :group 'comm)

(defcustom wttrin-font-name "Liberation Mono"
  "Preferred monospaced font name for weather display."
  :group 'wttrin
  :type 'string)

(defcustom wttrin-font-height 130
  "Preferred font height for weather display."
  :group 'wttrin
  :type 'integer)

(defcustom wttrin-default-locations '("Honolulu, HI"
									  "Berkeley, CA"
									  "New Orleans, LA"
									  "New York, NY"
                                      "London, GB"
                                      "Paris, FR"
                                      "Berlin, DE"
                                      "Naples, IT"
                                      "Athens, GR"
									  "Kyiv, UA"
									  "Tokyo, JP"
                                      "Taipei, TW")
  "Specify default locations list for quick completion."
  :group 'wttrin
  :type '(repeat string))

(defcustom wttrin-default-languages
  '("Accept-Language" . "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4")
  "Specify default HTTP request Header for Accept-Language."
  :group 'wttrin
  :type '(cons (string :tag "Header") (string :tag "Language codes")))

(defcustom wttrin-unit-system nil
  "Specify units of measurement.
Use \='m\=' for \='metric\=', \='u\=' for \='USCS\=', or nil for location based
units (default)."
  :group 'wttrin
  :type 'string)


(defcustom wttrin-cache-ttl 900  ; 15 minutes
  "Time to live for cached weather data in seconds."
  :group 'wttrin
  :type 'integer)

(defcustom wttrin-cache-max-entries 50
  "Maximum number of entries to keep in cache."
  :group 'wttrin
  :type 'integer)

(defconst wttrin--cache-cleanup-percentage 0.20
  "Percentage of cache entries to remove when max size is exceeded.
When cache reaches `wttrin-cache-max-entries', remove the oldest 20%
to avoid frequent cleanup cycles.  This value (0.20) means remove 1/5
of entries, providing a reasonable buffer before the next cleanup.")

(defcustom wttrin-mode-line-favorite-location nil
  "Favorite location to display weather for in the mode-line.
When nil, mode-line weather display is disabled.
Set to a location string (e.g., \"New Orleans, LA\") to enable.
The weather icon and tooltip will update automatically in the background."
  :group 'wttrin
  :type '(choice (const :tag "Disabled" nil)
                 (string :tag "Location")))

(defcustom wttrin-mode-line-refresh-interval 900
  "Interval in seconds to refresh mode-line weather data.
Default is 900 seconds (15 minutes)."
  :group 'wttrin
  :type 'integer)

(defcustom wttrin-mode-line-startup-delay 3
  "Seconds to delay initial mode-line weather fetch after Emacs starts.
This allows network stack and daemon initialization to complete before
fetching weather data.  Must be between 1 and 10 seconds."
  :group 'wttrin
  :type '(restricted-sexp :match-alternatives
                          ((lambda (val)
                             (and (integerp val)
                                  (>= val 1)
                                  (<= val 10))))))

(defcustom wttrin-mode-line-emoji-font "Noto Color Emoji"
  "Font family to use for mode-line weather emoji.
Common color emoji fonts include:
- \"Noto Color Emoji\" (Linux)
- \"Apple Color Emoji\" (macOS)
- \"Segoe UI Emoji\" (Windows)
- \"Twitter Color Emoji\"
Set to nil to use default font (may render as monochrome)."
  :group 'wttrin
  :type '(choice (const :tag "Use default font" nil)
                 (string :tag "Font family name")))

(defcustom wttrin-mode-line-auto-enable nil
  "If non-nil, automatically enable mode-line weather display when loading wttrin.
When enabled, weather for `wttrin-mode-line-favorite-location' will appear
in the mode-line automatically.  You can also manually toggle the mode-line
display with `wttrin-mode-line-mode'."
  :group 'wttrin
  :type 'boolean)

(defcustom wttrin-debug nil
  "Enable debug functions for troubleshooting wttrin behavior.
When non-nil, loads wttrin-debug.el which provides:
- Automatic mode-line diagnostic logging when wttrin runs
- Raw weather data saved to timestamped files in variable
  `temporary-file-directory'
- Interactive debug commands for troubleshooting

Set this to t BEFORE loading wttrin, typically in your init file:
  (setq wttrin-debug t)
  (require \\='wttrin)"
  :group 'wttrin
  :type 'boolean)

;; Load debug functions if enabled
(when wttrin-debug
  (require 'wttrin-debug
           (expand-file-name "wttrin-debug.el"
                             (file-name-directory (or load-file-name buffer-file-name)))
           t))

(defvar wttrin--cache (make-hash-table :test 'equal)
  "Cache for weather data: cache-key -> (timestamp . data).")

(defvar wttrin--force-refresh nil
  "When non-nil, bypass cache on next fetch.")

(defvar wttrin-mode-line-string nil
  "Mode-line string showing weather for favorite location.")
;;;###autoload(put 'wttrin-mode-line-string 'risky-local-variable t)
(put 'wttrin-mode-line-string 'risky-local-variable t)

(defvar wttrin--mode-line-timer nil
  "Timer object for mode-line weather refresh.")

(defvar wttrin--mode-line-tooltip-data nil
  "Cached full weather data for tooltip display.")

(defvar wttrin--mode-line-map
  (let ((map (make-sparse-keymap)))
    (define-key map [mode-line mouse-1] 'wttrin-mode-line-click)
    (define-key map [mode-line mouse-3] 'wttrin-mode-line-force-refresh)
    map)
  "Keymap for mode-line weather widget interactions.
Left-click: refresh weather and open buffer.
Right-click: force-refresh cache and update tooltip.")

(defun wttrin-additional-url-params ()
  "Concatenates extra information into the URL."
  (if wttrin-unit-system
      (concat "?" wttrin-unit-system)
    "?"))

(defun wttrin--build-url (query)
  "Build wttr.in URL for QUERY with configured parameters.
This is a pure function with no side effects, suitable for testing."
  (when (null query)
    (error "Query cannot be nil"))
  (concat "https://wttr.in/"
          (url-hexify-string query)
          (wttrin-additional-url-params)
          "A"))

(defun wttrin--extract-response-body ()
  "Extract and decode HTTP response body from current buffer.
Skips headers and returns UTF-8 decoded body.
Returns nil on error.  Kills buffer when done."
  (condition-case err
      (unwind-protect
          (progn
            (goto-char (point-min))
            (re-search-forward "\r?\n\r?\n" nil t)
            (let ((body (decode-coding-string
                         (buffer-substring-no-properties (point) (point-max))
                         'utf-8)))
              (when (featurep 'wttrin-debug)
                (wttrin--debug-log "wttrin--extract-response-body: Successfully fetched %d bytes"
                                   (length body)))
              body))
        (ignore-errors (kill-buffer (current-buffer))))
    (error
     (when (featurep 'wttrin-debug)
       (wttrin--debug-log "wttrin--extract-response-body: Error - %s"
                          (error-message-string err)))
     (ignore-errors (kill-buffer (current-buffer)))
     nil)))

(defun wttrin--handle-fetch-callback (status callback)
  "Handle `url-retrieve' callback STATUS and invoke CALLBACK with result.
Extracts response body or handles errors, then calls CALLBACK with data or nil."
  (when (featurep 'wttrin-debug)
    (wttrin--debug-log "wttrin--handle-fetch-callback: Invoked with status = %S" status))
  (let ((data nil))
    (if (plist-get status :error)
        (when (featurep 'wttrin-debug)
          (wttrin--debug-log "wttrin--handle-fetch-callback: Network error - %s"
                             (cdr (plist-get status :error))))
      (setq data (wttrin--extract-response-body)))
    (condition-case err
        (progn
          (when (featurep 'wttrin-debug)
            (wttrin--debug-log "wttrin--handle-fetch-callback: Calling user callback with %s"
                               (if data (format "%d bytes" (length data)) "nil")))
          (funcall callback data))
      (error
       (when (featurep 'wttrin-debug)
         (wttrin--debug-log "wttrin--handle-fetch-callback: Error in user callback - %s"
                            (error-message-string err)))
       (message "wttrin: Error in callback - %s" (error-message-string err))))))

(defun wttrin--fetch-url (url callback)
  "Asynchronously fetch URL and call CALLBACK with decoded response.
CALLBACK is called with the weather data string when ready, or nil on error.
Handles header skipping, UTF-8 decoding, and error handling automatically."
  (when (featurep 'wttrin-debug)
    (wttrin--debug-log "wttrin--fetch-url: Starting fetch for URL: %s" url))
  (let ((url-request-extra-headers (list wttrin-default-languages))
        (url-user-agent "curl"))
    (url-retrieve url
                  (lambda (status)
                    (wttrin--handle-fetch-callback status callback)))))

(defun wttrin-fetch-raw-string (query callback)
  "Asynchronously fetch weather information for QUERY.
CALLBACK is called with the weather data string when ready, or nil on error."
  (wttrin--fetch-url (wttrin--build-url query) callback))

(defun wttrin-exit ()
  "Exit the wttrin buffer."
  (interactive)
  (quit-window t))

(defun wttrin-requery ()
  "Kill buffer and requery wttrin."
  (interactive)
  (let ((new-location (completing-read
                       "Location Name: " wttrin-default-locations nil nil
                       (when (= (length wttrin-default-locations) 1)
                         (car wttrin-default-locations)))))
    (when (get-buffer "*wttr.in*")
      (kill-buffer "*wttr.in*"))
    (wttrin-query new-location)))

(defvar wttrin-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map (kbd "a") 'wttrin-requery)
    (define-key map (kbd "g") 'wttrin-requery-force)
    ;; Note: 'q' is bound to quit-window by special-mode
    map)
  "Keymap for wttrin-mode.")

(define-derived-mode wttrin-mode special-mode "Wttrin"
  "Major mode for displaying wttr.in weather information.

Weather data is displayed in a read-only buffer with the following keybindings:

\\{wttrin-mode-map}"
  (buffer-disable-undo)
  ;; Use face-remap instead of buffer-face-mode to preserve xterm-color faces
  (face-remap-add-relative 'default
                           :family wttrin-font-name
                           :height wttrin-font-height))

(defun wttrin--save-debug-data (location-name raw-string)
  "Save RAW-STRING to a timestamped debug file for LOCATION-NAME.
Returns the path to the saved file."
  (let* ((timestamp (format-time-string "%Y%m%d-%H%M%S"))
         (filename (format "wttrin-debug-%s.txt" timestamp))
         (filepath (expand-file-name filename temporary-file-directory)))
    (with-temp-file filepath
      (insert (format "Location: %s\n" location-name))
      (insert (format "Timestamp: %s\n" (format-time-string "%Y-%m-%d %H:%M:%S")))
      (insert (format "wttrin-unit-system: %s\n" wttrin-unit-system))
      (insert "\n--- Raw Response ---\n\n")
      (insert raw-string))
    (when (featurep 'wttrin-debug)
      (wttrin--debug-log "Debug data saved to: %s" filepath))
    filepath))

(defun wttrin--validate-weather-data (raw-string)
  "Check if RAW-STRING has valid weather data.
Return t if valid, nil if missing or contains errors."
  (not (or (null raw-string) (string-match "ERROR" raw-string))))

(defun wttrin--process-weather-content (raw-string)
  "Process RAW-STRING: apply ANSI filtering and remove verbose lines.
Returns processed string ready for display."
  (require 'xterm-color)
  (let ((processed (xterm-color-filter raw-string)))
    ;; Remove verbose Location: coordinate line
    (with-temp-buffer
      (insert processed)
      (goto-char (point-min))
      (while (re-search-forward "^\\s-*Location:.*\\[.*\\].*$" nil t)
        (delete-region (line-beginning-position) (1+ (line-end-position))))
      (buffer-string))))

(defun wttrin--add-buffer-instructions ()
  "Add user instructions at bottom of current buffer."
  (goto-char (point-max))
  (insert "\n\nPress: [a] for another location [g] to refresh [q] to quit"))

(defun wttrin--display-weather (location-name raw-string)
  "Display weather data RAW-STRING for LOCATION-NAME in weather buffer."
  ;; Save debug data if enabled
  (when wttrin-debug
    (wttrin--save-debug-data location-name raw-string))

  (if (not (wttrin--validate-weather-data raw-string))
      (message "Cannot retrieve weather data. Perhaps the location was misspelled?")
    (let ((buffer (get-buffer-create (format "*wttr.in*"))))
      (switch-to-buffer buffer)

      ;; Enable wttrin-mode first (calls kill-all-local-variables)
      ;; This must be done before setting any buffer-local variables
      (wttrin-mode)

      ;; Temporarily allow editing
      (let ((inhibit-read-only t))
        (erase-buffer)
        ;; Initialize xterm-color state AFTER wttrin-mode to prevent it being wiped
        (require 'xterm-color)
        (setq-local xterm-color--state :char)
        (insert (wttrin--process-weather-content raw-string))
        (wttrin--add-buffer-instructions)
        ;; align buffer to top
        (goto-char (point-min)))

      ;; Set location after mode initialization (mode calls kill-all-local-variables)
      (setq-local wttrin--current-location location-name)

      ;; Auto-generate debug diagnostics if debug mode is enabled
      (when (featurep 'wttrin-debug)
        (wttrin--debug-mode-line-info)))))

(defun wttrin-query (location-name)
  "Asynchronously query weather of LOCATION-NAME, display result when ready."
  (let ((buffer (get-buffer-create (format "*wttr.in*"))))
    (switch-to-buffer buffer)
    (setq buffer-read-only nil)
    (erase-buffer)
    (insert "Loading weather for " location-name "...")
    (setq buffer-read-only t)
    (wttrin--get-cached-or-fetch
     location-name
     (lambda (raw-string)
       (when (buffer-live-p buffer)
         (with-current-buffer buffer
           (wttrin--display-weather location-name raw-string)))))))

(defun wttrin--make-cache-key (location)
  "Create cache key from LOCATION and current settings."
  (concat location "|" (or wttrin-unit-system "default")))

(defun wttrin--get-cached-or-fetch (location callback)
  "Asynchronously get cached weather for LOCATION or fetch if expired.
CALLBACK is called with the weather data string when ready, or nil on error."
  (let* ((cache-key (wttrin--make-cache-key location))
         (cached (gethash cache-key wttrin--cache))
         (timestamp (car cached))
         (data (cdr cached))
         (now (float-time)))
    (if (and cached
             (< (- now timestamp) wttrin-cache-ttl)
             (not wttrin--force-refresh))
        ;; Return cached data immediately
        (funcall callback data)
      ;; Fetch fresh data asynchronously
      (wttrin-fetch-raw-string
       location
       (lambda (fresh-data)
         (if fresh-data
             (progn
               (wttrin--cleanup-cache-if-needed)
               (puthash cache-key (cons now fresh-data) wttrin--cache)
               (funcall callback fresh-data))
           ;; On error, return stale cache if available
           (if cached
               (progn
                 (message "Failed to fetch new data, using cached version")
                 (funcall callback data))
             (funcall callback nil))))))))

(defun wttrin--get-cache-entries-by-age ()
  "Return list of (key . timestamp) pairs sorted oldest-first.
Extracts all cache entries and sorts them by timestamp in ascending order.
Returns a list where each element is a cons cell (key . timestamp)."
  (let ((entries nil))
    (maphash (lambda (key value)
               (push (cons key (car value)) entries))  ; car value = timestamp
             wttrin--cache)
    (sort entries (lambda (a b) (< (cdr a) (cdr b))))))

(defun wttrin--cleanup-cache-if-needed ()
  "Remove oldest entries if cache exceeds max size.
Removes oldest entries based on `wttrin--cache-cleanup-percentage'
when cache count exceeds `wttrin-cache-max-entries'.
This creates headroom to avoid frequent cleanups."
  (when (> (hash-table-count wttrin--cache) wttrin-cache-max-entries)
    (let* ((entries-by-age (wttrin--get-cache-entries-by-age))
           (num-to-remove (floor (* (length entries-by-age)
                                    wttrin--cache-cleanup-percentage))))
      (dotimes (i num-to-remove)
        (remhash (car (nth i entries-by-age)) wttrin--cache)))))

(defun wttrin-clear-cache ()
  "Clear the weather cache."
  (interactive)
  (clrhash wttrin--cache)
  (message "Weather cache cleared"))

(defvar-local wttrin--current-location nil
  "Current location displayed in this weather buffer.")

(defun wttrin-requery-force ()
  "Force refresh weather data for current location, bypassing cache."
  (interactive)
  (if wttrin--current-location
      (let ((wttrin--force-refresh t))
        (message "Refreshing weather data...")
        (wttrin-query wttrin--current-location))
    (message "No location to refresh")))

;;; Mode-line weather display

(defun wttrin--mode-line-fetch-weather ()
  "Fetch weather for favorite location and update mode-line display.
Uses wttr.in custom format for concise weather with emoji."
  (when (featurep 'wttrin-debug)
    (wttrin--debug-log "mode-line-fetch: Starting fetch for %s" wttrin-mode-line-favorite-location))
  (when wttrin-mode-line-favorite-location
    (let* ((location wttrin-mode-line-favorite-location)
           ;; Custom format: location + emoji + temp + conditions
           ;; %l=location, %c=weather emoji, %t=temp, %C=conditions
           ;; Note: unit system must come BEFORE format in query string
           (format-params (if wttrin-unit-system
                              (concat "?" wttrin-unit-system "&format=%l:+%c+%t+%C")
                            "?format=%l:+%c+%t+%C"))
           (url (concat "https://wttr.in/"
                       (url-hexify-string location)
                       format-params)))
      (when (featurep 'wttrin-debug)
        (wttrin--debug-log "mode-line-fetch: URL = %s" url))
      (wttrin--fetch-url
       url
       (lambda (data)
         (if data
             (let ((trimmed-data (string-trim data)))
               (when (featurep 'wttrin-debug)
                 (wttrin--debug-log "mode-line-fetch: Received data = %S" trimmed-data))
               (wttrin--mode-line-update-display trimmed-data))
           (when (featurep 'wttrin-debug)
             (wttrin--debug-log "mode-line-fetch: No data received (network error)"))))))))

(defun wttrin--mode-line-update-display (weather-string)
  "Update mode-line display with WEATHER-STRING.
Extracts emoji for mode-line, stores full info for tooltip.
WEATHER-STRING format: \"Location: emoji temp conditions\",
e.g., \"Paris: ☀️ +61°F Clear\"."
  (when (featurep 'wttrin-debug)
    (wttrin--debug-log "mode-line-display: Updating display with: %S" weather-string))
  ;; Store full weather info for tooltip
  (setq wttrin--mode-line-tooltip-data weather-string)
  ;; Extract just the emoji for mode-line display
  ;; Format is "Location: emoji +temp conditions"
  ;; We want just the emoji (first character after ": ")
  (let* ((emoji (if (string-match ":\\s-*\\(.\\)" weather-string)
                    (match-string 1 weather-string)
                  "?"))  ; Fallback if parsing fails
         ;; Force color emoji rendering by setting font family
         (emoji-with-font (if wttrin-mode-line-emoji-font
                              (propertize emoji
                                          'face (list :family wttrin-mode-line-emoji-font
                                                      :height 1.0))
                            emoji)))
    (when (featurep 'wttrin-debug)
      (wttrin--debug-log "mode-line-display: Extracted emoji = %S, font = %s"
                         emoji wttrin-mode-line-emoji-font))
    (setq wttrin-mode-line-string
          (propertize (concat " " emoji-with-font)
                      'help-echo (lambda (_window _object _pos)
                                   (or wttrin--mode-line-tooltip-data
                                       (format "Weather for %s\nClick to refresh"
                                               wttrin-mode-line-favorite-location)))
                      'mouse-face 'mode-line-highlight
                      'local-map wttrin--mode-line-map)))
  (force-mode-line-update t)
  (when (featurep 'wttrin-debug)
    (wttrin--debug-log "mode-line-display: Complete. mode-line-string set = %s, tooltip = %S"
                       (if wttrin-mode-line-string "YES" "NO")
                       wttrin--mode-line-tooltip-data)))

(defun wttrin-mode-line-click ()
  "Handle left-click on mode-line weather widget.
Check cache, refresh if needed, then open weather buffer."
  (interactive)
  (when wttrin-mode-line-favorite-location
    (wttrin wttrin-mode-line-favorite-location)))

(defun wttrin-mode-line-force-refresh ()
  "Handle right-click on mode-line weather widget.
Force-refresh cache and update tooltip without opening buffer."
  (interactive)
  (when wttrin-mode-line-favorite-location
    (let ((wttrin--force-refresh t))
      (wttrin--mode-line-fetch-weather))))

(defun wttrin--mode-line-start ()
  "Start mode-line weather display and refresh timer."
  (when (featurep 'wttrin-debug)
    (wttrin--debug-log "wttrin mode-line: Starting mode-line display (location=%s, interval=%s)"
                       wttrin-mode-line-favorite-location
                       wttrin-mode-line-refresh-interval))
  (when wttrin-mode-line-favorite-location
    ;; Delay initial fetch to allow network to initialize during startup
    (run-at-time wttrin-mode-line-startup-delay nil #'wttrin--mode-line-fetch-weather)
    ;; Set up refresh timer (starts after the interval from now)
    (when wttrin--mode-line-timer
      (cancel-timer wttrin--mode-line-timer))
    (setq wttrin--mode-line-timer
          (run-at-time wttrin-mode-line-refresh-interval
                      wttrin-mode-line-refresh-interval
                      #'wttrin--mode-line-fetch-weather))
    (when (featurep 'wttrin-debug)
      (wttrin--debug-log "wttrin mode-line: Initial fetch scheduled in %s seconds, then every %s seconds"
                         wttrin-mode-line-startup-delay
                         wttrin-mode-line-refresh-interval))))

(defun wttrin--mode-line-stop ()
  "Stop mode-line weather display and cancel timer."
  (when (featurep 'wttrin-debug)
    (wttrin--debug-log "wttrin mode-line: Stopping mode-line display"))
  (when wttrin--mode-line-timer
    (cancel-timer wttrin--mode-line-timer)
    (setq wttrin--mode-line-timer nil))
  (setq wttrin-mode-line-string nil)
  (setq wttrin--mode-line-tooltip-data nil)
  (force-mode-line-update t))

;;;###autoload
(define-minor-mode wttrin-mode-line-mode
  "Toggle weather display in mode-line.
When enabled, shows weather for `wttrin-mode-line-favorite-location'."
  :global t
  :lighter (:eval wttrin-mode-line-string)
  (if wttrin-mode-line-mode
      (progn
        (when (featurep 'wttrin-debug)
          (wttrin--debug-log "wttrin mode-line: Mode enabled"))
        ;; Delay network activity until Emacs is fully initialized
        (if (and (not after-init-time) (not noninteractive))
            (progn
              (when (featurep 'wttrin-debug)
                (wttrin--debug-log "wttrin mode-line: Deferring start until after-init-hook"))
              (add-hook 'after-init-hook #'wttrin--mode-line-start))
          (wttrin--mode-line-start))
        ;; Add modeline string to global-mode-string for custom modelines
        (if global-mode-string
            (add-to-list 'global-mode-string 'wttrin-mode-line-string 'append)
          (setq global-mode-string '("" wttrin-mode-line-string)))
        (when (featurep 'wttrin-debug)
          (wttrin--debug-log "wttrin mode-line: Added to global-mode-string = %S" global-mode-string)))
    (when (featurep 'wttrin-debug)
      (wttrin--debug-log "wttrin mode-line: Mode disabled"))
    (wttrin--mode-line-stop)
    ;; Remove from global-mode-string
    (setq global-mode-string
          (delq 'wttrin-mode-line-string global-mode-string))))

;;;###autoload
(defun wttrin (location)
  "Display weather information for LOCATION.
Weather data is fetched asynchronously to avoid blocking Emacs."
  (interactive
   (list
    (completing-read "Location Name: " wttrin-default-locations nil nil
                     (when (= (length wttrin-default-locations) 1)
                       (car wttrin-default-locations)))))
  (wttrin-query location))

;; Auto-enable mode-line display if requested
(when wttrin-mode-line-auto-enable
  (wttrin-mode-line-mode 1))

(provide 'wttrin)
;;; wttrin.el ends here