aboutsummaryrefslogtreecommitdiff
path: root/cmds/serve.go
blob: 92aa64ca61bf63066258b388c3a9b09f8978e6ec (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
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
// Serve command: HTTP server for web UI and APIs.
//
// Two main flows: live-feed (cached + background refresh) and tools (on-demand scoring).
// Live-feed rescans all configured RSS feeds on a timer (default 24h), caches results,
// serves filtered articles via web UI and JSON/RSS APIs.
// Tools provides real-time /score (single title) and /scan (ad-hoc feed) endpoints.
// Background refresh continues despite individual feed failures; RWMutex allows
// many concurrent readers with exclusive writer updates.
// Templates are embedded for single-binary deployment.
package cmds

import (
	"bufio"
	"context"
	"embed"
	"encoding/json"
	"flag"
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
	"sync"
	"syscall"
	"time"

	"github.com/PuerkitoBio/goquery"
	"github.com/mmcdole/gofeed"
	"scholscan/core"
)

//go:embed templates/*.html
var templateFS embed.FS

// ============================================================================
// ┏━╸┏┳┓╺┳┓   ┏━┓┏┓  ┏┓
// ┃  ┃┃┃ ┃┃   ┃ ┃┣┻┓  ┃
// ┗━╸╹ ╹╺┻┛   ┗━┛┗━┛┗━┛
// ============================================================================

type ServeCommand struct {
	Port            int
	RSSWorldPath    string
	RefreshInterval string
	ModelPath       string
	Title           string

	// Parsed interval
	refreshInterval time.Duration
	// Loaded model (cached)
	model   *core.ModelEnvelope
	modelMu sync.RWMutex
	// Cached filtered RSS results and timestamp.
	// RWMutex allows many concurrent readers (HTTP handlers) with exclusive writer (background refresh).
	filteredResults     []*core.Article
	filteredResultsTime time.Time
	resultsMu           sync.RWMutex
	// Loaded templates
	tmpl *template.Template
}

func (c *ServeCommand) Name() string { return "serve" }

// Init configures the serve command with robust input validation.
// Prevents directory traversal, validates paths, and sets sensible defaults.
// Ensures only one configuration is possible to reduce runtime complexity.
func (c *ServeCommand) Init(args []string) error {
	fs := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
	fs.Usage = func() {
		fmt.Fprint(fs.Output(), `Usage: scholscan serve [options]

		Start HTTP server for filtered RSS and scoring web UI.

		Flags:
		`)
		fs.PrintDefaults()
		fmt.Fprint(fs.Output(), `
		Examples:
		scholscan serve --port 8080 --rss-world rss_world.txt --model model.json
		scholscan serve --refresh-interval 24h --model ./model.json --rss-world feeds.txt
		`)
	}

	fs.IntVar(&c.Port, "port", 8080, "Port to listen on")
	fs.StringVar(&c.RSSWorldPath, "rss-world", "rss_world.txt", "Path to RSS world file (one feed URL per line)")
	fs.StringVar(&c.RefreshInterval, "refresh-interval", "24h", "Interval for background rescans (e.g., 24h, 1h)")
	fs.StringVar(&c.ModelPath, "model", "model.json", "Path to trained model JSON file")
	fs.StringVar(&c.Title, "title", "", "Custom title for the web interface")

	if err := fs.Parse(args); err != nil {
		return err
	}

	if fs.NArg() != 0 {
		return fmt.Errorf("unexpected arguments provided: %v", fs.Args())
	}

	// Parse refresh interval
	interval, err := time.ParseDuration(c.RefreshInterval)
	if err != nil {
		return fmt.Errorf("invalid refresh-interval %q: %w", c.RefreshInterval, err)
	}
	c.refreshInterval = interval

	if strings.Contains(filepath.Clean(c.RSSWorldPath), "..") {
		return fmt.Errorf("invalid rss-world path: directory traversal not allowed")
	}
	if strings.Contains(filepath.Clean(c.ModelPath), "..") {
		return fmt.Errorf("invalid model path: directory traversal not allowed")
	}

	return nil
}

func (c *ServeCommand) Run(stdin io.Reader, stdout io.Writer) error {
	log.Printf("Starting scholscan server on port %d", c.Port)

	// Initialize filteredResultsTime to server start time
	c.resultsMu.Lock()
	c.filteredResultsTime = time.Now()
	c.resultsMu.Unlock()

	// Load templates at startup
	tmpl, err := template.ParseFS(templateFS, "templates/*.html")
	if err != nil {
		return fmt.Errorf("failed to parse templates: %w", err)
	}
	c.tmpl = tmpl
	log.Printf("Templates loaded successfully")

	// Load model at startup
	model, err := c.loadModel()
	if err != nil {
		return fmt.Errorf("failed to load model at startup: %w", err)
	}
	c.modelMu.Lock()
	c.model = model
	c.modelMu.Unlock()

	log.Printf("Model loaded successfully")

	// Start background ticker for periodic refresh
	ticker := time.NewTicker(c.refreshInterval)
	go c.backgroundRefresh(ticker)

	// Perform initial scan asynchronously
	go func() {
		log.Println("Starting initial feed scan...")
		if err := c.refreshFilteredResults(); err != nil {
			log.Printf("Warning: initial scan failed: %v", err)
		} else {
			c.resultsMu.RLock()
			count := len(c.filteredResults)
			c.resultsMu.RUnlock()
			log.Printf("Initial scan complete, %d articles filtered", count)
		}
	}()

	// Setup HTTP handlers
	http.HandleFunc("/", c.handleRoot)
	http.HandleFunc("/live-feed", c.handleLiveFeed)
	http.HandleFunc("/tools", c.handleTools)
	http.HandleFunc("/score", c.handleScore)
	http.HandleFunc("/scan", c.handleScan)
	http.HandleFunc("/api/filtered/feed", c.handleFilteredFeed)
	http.HandleFunc("/api/filtered/rss", c.handleFilteredRSS)
	http.HandleFunc("/api/health", c.handleHealth)

	// Setup server with graceful shutdown
	server := &http.Server{
		Addr:         fmt.Sprintf(":%d", c.Port),
		Handler:      http.DefaultServeMux,
		ReadTimeout:  core.DefaultReadTimeout,
		WriteTimeout: core.DefaultWriteTimeout,
		IdleTimeout:  core.DefaultIdleTimeout,
	}

	// Handle shutdown signals
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		<-sigChan
		log.Println("Shutdown signal received")
		ticker.Stop()
		ctx, cancel := context.WithTimeout(context.Background(), core.DefaultShutdownTimeout)
		defer cancel()
		if err := server.Shutdown(ctx); err != nil {
			log.Printf("Server shutdown error: %v", err)
		}
	}()

	log.Printf("Server listening on http://localhost:%d", c.Port)
	if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		return fmt.Errorf("server error: %w", err)
	}

	return nil
}

// ============================================================================
// ┏━╸┏━┓┏━┓┏━╸   ╻  ┏━┓┏━╸╻┏━╸
// ┃  ┃ ┃┣┳┛┣╸    ┃  ┃ ┃┃╺┓┃┃
// ┗━╸┗━┛╹┗╸┗━╸   ┗━╸┗━┛┗━┛╹┗━╸
// ============================================================================

func (c *ServeCommand) loadModel() (*core.ModelEnvelope, error) {
	f, err := os.Open(c.ModelPath)
	if err != nil {
		return nil, fmt.Errorf("failed to open model file %s: %w", c.ModelPath, err)
	}
	defer f.Close()

	var model core.ModelEnvelope
	if err := json.NewDecoder(f).Decode(&model); err != nil {
		return nil, fmt.Errorf("failed to decode model: %w", err)
	}

	return &model, nil
}

func (c *ServeCommand) scoreArticle(article *core.Article, vectorizer *core.TFIDFVectorizer, model *core.ModelEnvelope) float64 {
	docs := []string{strings.TrimSpace(article.Title)}
	vectors := vectorizer.Transform(docs)

	if len(vectors) == 0 || len(vectors[0]) == 0 {
		return 0.0
	}

	score, err := core.PredictScore(vectors[0], model.Weights)
	if err != nil {
		// Return 0.0 on error (below threshold). Malformed articles don't break the display,
		// they just get filtered out. Log the error for diagnostics.
		log.Printf("Error scoring article: %v", err)
		return 0.0
	}

	return score
}

func (c *ServeCommand) getThreshold(model *core.ModelEnvelope) (float64, error) {
	if model.Meta != nil {
		if threshold, ok := model.Meta["recommended_threshold"].(float64); ok {
			return threshold, nil
		}
	}
	return core.DefaultScoreThreshold, nil
}

// scoreAndFormatArticles scores a list of articles and returns them formatted for templates.
// Articles are scored using the model and vectorizer, then returned with human-readable ratings.
func (c *ServeCommand) scoreAndFormatArticles(articles []*core.Article, vectorizer *core.TFIDFVectorizer, model *core.ModelEnvelope, threshold float64) []map[string]interface{} {
	type ArticleResponse struct {
		Title  string  `json:"title"`
		URL    string  `json:"url"`
		Source string  `json:"source,omitempty"`
		Rating int     `json:"rating"`
		Score  float64 `json:"score"`
	}

	scored := make([]ArticleResponse, 0, len(articles))
	for _, article := range articles {
		score := c.scoreArticle(article, vectorizer, model)
		rating := core.ScoreToScale(score, threshold)

		scored = append(scored, ArticleResponse{
			Title:  article.Title,
			URL:    article.URL,
			Source: article.Source,
			Rating: rating,
			Score:  score,
		})
	}

	result := make([]map[string]interface{}, len(scored))
	for i, a := range scored {
		result[i] = map[string]interface{}{
			"Title":  a.Title,
			"URL":    a.URL,
			"Source": a.Source,
			"Rating": a.Rating,
			"Score":  a.Score,
		}
	}
	return result
}

// ============================================================================
// ┏━┓┏━┓┏━┓   ┏━┓╺┳╸╻ ╻┏━╸┏━╸
// ┣┳┛┗━┓┗━┓   ┗━┓ ┃ ┃ ┃┣╸ ┣╸
// ╹┗╸┗━┛┗━┛   ┗━┛ ╹ ┗━┛╹  ╹
// ============================================================================

func (c *ServeCommand) readRSSWorldFeeds() ([]string, error) {
	f, err := os.Open(c.RSSWorldPath)
	if err != nil {
		return nil, fmt.Errorf("failed to open rss_world file %s: %w", c.RSSWorldPath, err)
	}
	defer f.Close()

	var feeds []string
	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line != "" && !strings.HasPrefix(line, "#") {
			feeds = append(feeds, line)
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("error reading rss_world file: %w", err)
	}

	return feeds, nil
}

func (c *ServeCommand) refreshFilteredResults() error {
	feeds, err := c.readRSSWorldFeeds()
	if err != nil {
		return err
	}

	c.modelMu.RLock()
	model := c.model
	c.modelMu.RUnlock()

	if model == nil {
		return fmt.Errorf("model not loaded")
	}

	// Scan all feeds. Continue on individual feed failures to maximize results.
	// RSS feeds are often flaky; one down shouldn't prevent others from being processed.
	var allArticles []*core.Article
	for _, feed := range feeds {
		articles, err := c.fetchRSSFeed(feed)
		if err != nil {
			log.Printf("Warning: failed to fetch feed %s: %v", feed, err)
			continue
		}
		allArticles = append(allArticles, articles...)
	}

	// Score and filter articles
	threshold, err := c.getThreshold(model)
	if err != nil {
		return err
	}

	vectorizer := core.CreateVectorizerFromModel(model)

	filtered := make([]*core.Article, 0, len(allArticles))
	for _, article := range allArticles {
		score := c.scoreArticle(article, vectorizer, model)
		if score >= threshold {
			// Create a copy with score to avoid reference issues
			articleCopy := *article
			articleCopy.Score = &score
			filtered = append(filtered, &articleCopy)
		}
	}

	c.resultsMu.Lock()
	c.filteredResults = filtered
	c.filteredResultsTime = time.Now()
	c.resultsMu.Unlock()

	return nil
}

// backgroundRefresh runs in a goroutine, rescanning all RSS feeds on interval.
// Failures in individual feeds don't affect others - we log and continue.
func (c *ServeCommand) backgroundRefresh(ticker *time.Ticker) {
	for range ticker.C {
		log.Println("Background refresh started")
		if err := c.refreshFilteredResults(); err != nil {
			log.Printf("Background refresh error (continuing): %v", err)
		} else {
			c.resultsMu.RLock()
			count := len(c.filteredResults)
			c.resultsMu.RUnlock()
			log.Printf("Background refresh complete, %d articles filtered", count)
		}
	}
}

func (c *ServeCommand) fetchRSSFeed(url string) ([]*core.Article, error) {
	client := &http.Client{Timeout: core.DefaultHTTPTimeout}

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, fmt.Errorf("error building request: %w", err)
	}
	req.Header.Set("User-Agent", core.PoliteUserAgent)

	ctx, cancel := context.WithTimeout(context.Background(), core.DefaultHTTPTimeout)
	defer cancel()

	resp, err := client.Do(req.WithContext(ctx))
	if err != nil {
		return nil, fmt.Errorf("error fetching %s: %w", url, err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("HTTP %d from %s", resp.StatusCode, url)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("error reading response from %s: %w", url, err)
	}

	fp := gofeed.NewParser()
	feed, err := fp.Parse(strings.NewReader(string(body)))
	if err != nil {
		return nil, fmt.Errorf("error parsing feed from %s: %w", url, err)
	}

	var articles []*core.Article
	for _, item := range feed.Items {
		article := &core.Article{
			URL:    item.Link,
			Title:  strings.TrimSpace(item.Title),
			Source: feed.Title,
		}

		if item.PublishedParsed != nil {
			article.PublishedAt = item.PublishedParsed
		}

		if len(article.Title) >= core.MinTitleLength {
			articles = append(articles, article)
		}
	}

	return articles, nil
}

// ============================================================================
// ╻ ╻┏━╸┏┓    ╻ ╻╻
// ┃╻┃┣╸ ┣┻┓   ┃ ┃┃
// ┗┻┛┗━╸┗━┛   ┗━┛╹
// ============================================================================

func (c *ServeCommand) handleRoot(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	// Redirect to live feed
	http.Redirect(w, r, "/live-feed", http.StatusMovedPermanently)
}

func (c *ServeCommand) handleLiveFeed(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	c.resultsMu.RLock()
	articles := c.filteredResults
	resultsTime := c.filteredResultsTime
	c.resultsMu.RUnlock()

	c.modelMu.RLock()
	model := c.model
	c.modelMu.RUnlock()

	if model == nil {
		http.Error(w, "Model not loaded", http.StatusInternalServerError)
		return
	}

	threshold, _ := c.getThreshold(model)

	// Parse filter parameter (day, week, or all)
	filter := r.URL.Query().Get("filter")
	if filter == "" {
		filter = "all"
	}

	// Filter articles by date if needed
	now := time.Now()
	filtered := articles
	if filter == "day" || filter == "week" {
		var cutoff time.Time
		if filter == "day" {
			cutoff = now.Add(-24 * time.Hour)
		} else if filter == "week" {
			cutoff = now.Add(-7 * 24 * time.Hour)
		}

		filtered = make([]*core.Article, 0, len(articles))
		for _, article := range articles {
			// Always include articles without PublishedAt
			if article.PublishedAt == nil || article.PublishedAt.After(cutoff) {
				filtered = append(filtered, article)
			}
		}
	}

	// Convert articles to template format
	type TemplateArticle struct {
		Title       string
		URL         string
		Source      string
		Rating      int
		Score       float64
		PublishedAt string
	}

	templateArticles := make([]TemplateArticle, 0, len(filtered))
	for _, article := range filtered {
		score := 0.0
		if article.Score != nil {
			score = *article.Score
		}
		rating := core.ScoreToScale(score, threshold)

		publishedAt := ""
		if article.PublishedAt != nil {
			publishedAt = article.PublishedAt.Format("2006-01-02")
		}

		templateArticles = append(templateArticles, TemplateArticle{
			Title:       article.Title,
			URL:         article.URL,
			Source:      article.Source,
			Rating:      rating,
			Score:       score,
			PublishedAt: publishedAt,
		})
	}

	// Sort articles by score (highest first)
	sort.Slice(templateArticles, func(i, j int) bool {
		return templateArticles[i].Score > templateArticles[j].Score
	})

	data := map[string]interface{}{
		"Page":      "live-feed",
		"Articles":  templateArticles,
		"Threshold": threshold,
		"UpdatedAt": resultsTime.Format("2006-01-02 15:04:05"),
		"Filter":    filter,
		"Title":     displayTitle(c.Title),
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := c.tmpl.ExecuteTemplate(w, "live-feed", data); err != nil {
		http.Error(w, fmt.Sprintf("Template error: %v", err), http.StatusInternalServerError)
	}
}

func (c *ServeCommand) handleTools(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	data := map[string]interface{}{
		"Page":  "tools",
		"Title": displayTitle(c.Title),
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := c.tmpl.ExecuteTemplate(w, "tools", data); err != nil {
		http.Error(w, fmt.Sprintf("Template error: %v", err), http.StatusInternalServerError)
	}
}

func (c *ServeCommand) handleScore(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		c.handleTools(w, r)
		return
	}

	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	c.modelMu.RLock()
	model := c.model
	c.modelMu.RUnlock()

	if model == nil {
		http.Error(w, "Model not loaded", http.StatusInternalServerError)
		return
	}

	if err := r.ParseForm(); err != nil {
		http.Error(w, fmt.Sprintf("Failed to parse form: %v", err), http.StatusBadRequest)
		return
	}

	title := strings.TrimSpace(r.FormValue("title"))
	url := strings.TrimSpace(r.FormValue("url"))

	// If URL provided, fetch and extract title from it; otherwise use provided title.
	if url != "" {
		extractedTitle, err := extractTitleFromURL(url)
		if err != nil {
			c.renderResultsError(w, fmt.Sprintf("Failed to extract title from URL: %v", err), title)
			return
		}
		title = extractedTitle
	}

	// Validate input before scoring
	if valErr := c.validateTitle(title); valErr != "" {
		c.renderResultsError(w, valErr, title)
		return
	}

	vectorizer := core.CreateVectorizerFromModel(model)
	article := &core.Article{Title: title}
	score := c.scoreArticle(article, vectorizer, model)

	threshold, _ := c.getThreshold(model)
	rating := core.ScoreToScale(score, threshold)

	data := map[string]interface{}{
		"Page":          "tools",
		"IsScoreResult": true,
		"Title":         title,
		"Rating":        rating,
		"Score":         score,
		"Threshold":     threshold,
		"PageTitle":     displayTitle(c.Title),
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := c.tmpl.ExecuteTemplate(w, "results", data); err != nil {
		http.Error(w, fmt.Sprintf("Template error: %v", err), http.StatusInternalServerError)
	}
}

func (c *ServeCommand) handleScan(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		c.handleTools(w, r)
		return
	}

	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	c.modelMu.RLock()
	model := c.model
	c.modelMu.RUnlock()

	if model == nil {
		http.Error(w, "Model not loaded", http.StatusInternalServerError)
		return
	}

	if err := r.ParseForm(); err != nil {
		http.Error(w, fmt.Sprintf("Failed to parse form: %v", err), http.StatusBadRequest)
		return
	}

	feedURL := strings.TrimSpace(r.FormValue("feed_url"))

	// Validate and fetch the feed
	if valErr := c.validateFeedURL(feedURL); valErr != "" {
		c.renderScanResultsError(w, valErr, feedURL)
		return
	}

	articles, err := c.fetchRSSFeed(feedURL)
	if err != nil {
		c.renderScanResultsError(w, fmt.Sprintf("Failed to fetch feed: %v", err), feedURL)
		return
	}

	// Score articles
	threshold, _ := c.getThreshold(model)
	vectorizer := core.CreateVectorizerFromModel(model)
	scored := c.scoreAndFormatArticles(articles, vectorizer, model, threshold)

	sort.Slice(scored, func(i, j int) bool {
		iScore := scored[i]["Score"].(float64)
		jScore := scored[j]["Score"].(float64)
		return iScore > jScore
	})

	data := map[string]interface{}{
		"Page":         "tools",
		"IsScanResult": true,
		"FeedURL":      feedURL,
		"Articles":     scored,
		"Threshold":    threshold,
		"PageTitle":    displayTitle(c.Title),
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := c.tmpl.ExecuteTemplate(w, "results", data); err != nil {
		http.Error(w, fmt.Sprintf("Template error: %v", err), http.StatusInternalServerError)
	}
}

// ============================================================================
// ┏━┓┏━┓╻   ┏━╸┏┓╻╺┳┓┏━┓┏━┓╻┏┓╻╺┳╸┏━┓
// ┣━┫┣━┛┃   ┣╸ ┃┗┫ ┃┃┣━┛┃ ┃┃┃┗┫ ┃ ┗━┓
// ╹ ╹╹  ╹   ┗━╸╹ ╹╺┻┛╹  ┗━┛╹╹ ╹ ╹ ┗━┛
// ============================================================================

func (c *ServeCommand) handleFilteredFeed(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	c.resultsMu.RLock()
	articles := c.filteredResults
	resultsTime := c.filteredResultsTime
	c.resultsMu.RUnlock()

	c.modelMu.RLock()
	model := c.model
	c.modelMu.RUnlock()

	threshold, _ := c.getThreshold(model)

	type ArticleResponse struct {
		Title  string  `json:"title"`
		URL    string  `json:"url"`
		Source string  `json:"source,omitempty"`
		Rating int     `json:"rating"`
		Score  float64 `json:"score"`
	}

	scored := make([]ArticleResponse, 0, len(articles))
	for _, article := range articles {
		score := 0.0
		if article.Score != nil {
			score = *article.Score
		}
		rating := core.ScoreToScale(score, threshold)

		scored = append(scored, ArticleResponse{
			Title:  article.Title,
			URL:    article.URL,
			Source: article.Source,
			Rating: rating,
			Score:  score,
		})
	}

	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")

	if err := json.NewEncoder(w).Encode(map[string]interface{}{
		"total":      len(articles),
		"threshold":  threshold,
		"updated_at": resultsTime,
		"articles":   scored,
	}); err != nil {
		http.Error(w, "Failed to encode response", http.StatusInternalServerError)
	}
}

func (c *ServeCommand) handleFilteredRSS(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	c.resultsMu.RLock()
	articles := c.filteredResults
	c.resultsMu.RUnlock()

	c.modelMu.RLock()
	model := c.model
	c.modelMu.RUnlock()

	w.Header().Set("Content-Type", "application/rss+xml")
	w.Header().Set("Cache-Control", "public, max-age=3600")

	// Generate RSS feed
	fmt.Fprintf(w, `<?xml version="1.0" encoding="UTF-8"?>
	<rss version="2.0">
	<channel>
	<title>%s - Filtered Articles</title>
	<link>http://scholscan.local</link>
	<description>Articles filtered by your learned preferences (scored 1-10)</description>
	`, displayTitle(c.Title))

	for _, article := range articles {
		rawScore := 0.0
		if article.Score != nil {
			rawScore = *article.Score
		}

		threshold, _ := c.getThreshold(model)
		scaledScore := core.ScoreToScale(rawScore, threshold)

		title := escapeXML(article.Title)
		url := escapeXML(article.URL)
		description := fmt.Sprintf("SCHOLSCAN SCORE = %d/10 (raw: %.3f)", scaledScore, rawScore)

		fmt.Fprintf(w, `    <item>
		<title>%s</title>
		<link>%s</link>
		<description>%s</description>
		</item>
		`, title, url, description)
	}

	fmt.Fprint(w, `  </channel>
	</rss>`)
}

func (c *ServeCommand) handleHealth(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	c.modelMu.RLock()
	modelLoaded := c.model != nil
	c.modelMu.RUnlock()

	status := "ok"
	if !modelLoaded {
		status = "model_not_loaded"
		w.WriteHeader(http.StatusInternalServerError)
	}

	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(map[string]interface{}{
		"status":       status,
		"model_loaded": modelLoaded,
		"timestamp":    time.Now().Unix(),
	}); err != nil {
		http.Error(w, "Failed to encode response", http.StatusInternalServerError)
	}
}

// ============================================================================
// ╻ ╻┏━╸╻  ┏━┓┏━╸┏━┓┏━┓
// ┣━┫┣╸ ┃  ┣━┛┣╸ ┣┳┛┗━┓
// ╹ ╹┗━╸┗━╸╹  ┗━╸╹┗╸┗━┛
// ============================================================================

func displayTitle(custom string) string {
	if custom != "" {
		return custom
	}
	return "ScholScan"
}

// extractTitleFromURL fetches the content from a URL and extracts the title from the HTML.
// Designed to be resilient: tries multiple title sources, handles various URL formats,
// and provides meaningful error feedback if extraction fails.
func extractTitleFromURL(rawURL string) (string, error) {
	if rawURL == "" {
		return "", fmt.Errorf("empty URL")
	}

	// Check if it's a DOI
	if strings.HasPrefix(rawURL, "10.") {
		// Convert DOI to URL
		rawURL = fmt.Sprintf("https://doi.org/%s", rawURL)
	} else if !strings.HasPrefix(rawURL, "http://") && !strings.HasPrefix(rawURL, "https://") {
		rawURL = "https://" + rawURL
	}

	ctx, cancel := context.WithTimeout(context.Background(), core.DefaultContextTimeout)
	defer cancel()

	req, err := http.NewRequestWithContext(ctx, "GET", rawURL, nil)
	if err != nil {
		return "", fmt.Errorf("invalid URL: %w", err)
	}
	req.Header.Set("User-Agent", core.PoliteUserAgent)
	req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")

	resp, err := core.DoRequestWithRetry(ctx, core.DefaultHTTPClient, req)
	if err != nil {
		return "", fmt.Errorf("failed to fetch URL: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("HTTP %d: %s", resp.StatusCode, resp.Status)
	}

	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return "", fmt.Errorf("failed to parse HTML: %w", err)
	}

	// Fallback chain: <title> → og:title → twitter:title → <h1>
	// Different sites populate these differently; trying multiple increases success rate.
	title := ""

	if t := doc.Find("title").Text(); t != "" {
		title = strings.TrimSpace(t)
	}

	if title == "" {
		if t, exists := doc.Find(`meta[property="og:title"]`).Attr("content"); exists && t != "" {
			title = strings.TrimSpace(t)
		}
	}

	if title == "" {
		if t, exists := doc.Find(`meta[name="twitter:title"]`).Attr("content"); exists && t != "" {
			title = strings.TrimSpace(t)
		}
	}

	if title == "" {
		if t := doc.Find("h1").First().Text(); t != "" {
			title = strings.TrimSpace(t)
		}
	}

	if title == "" {
		return "", fmt.Errorf("could not extract title from page")
	}

	// Clean up common title patterns
	reClean := regexp.MustCompile(`\s*\|\s*`)
	title = reClean.ReplaceAllString(title, "")

	rePub := regexp.MustCompile(`^[^|]*\|\s*`)
	title = rePub.ReplaceAllString(title, "")
	title = strings.TrimSpace(title)

	if len(title) < 10 {
		return "", fmt.Errorf("extracted title too short: %q", title)
	}

	return title, nil
}

// validateTitle checks that a title is suitable for scoring.
// Returns an error message string if invalid, empty string if valid.
func (c *ServeCommand) validateTitle(title string) string {
	if strings.TrimSpace(title) == "" {
		return "Title cannot be empty"
	}
	if len(title) > 1000 {
		return "Title too long (max 1000 characters)"
	}
	return ""
}

// renderResultsError renders the results template with an error message.
func (c *ServeCommand) renderResultsError(w http.ResponseWriter, errMsg, title string) {
	data := map[string]interface{}{
		"Page":          "tools",
		"IsScoreResult": true,
		"Error":         errMsg,
		"Title":         title,
		"PageTitle":     displayTitle(c.Title),
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := c.tmpl.ExecuteTemplate(w, "results", data); err != nil {
		http.Error(w, fmt.Sprintf("Template error: %v", err), http.StatusInternalServerError)
	}
}

// validateFeedURL checks that a feed URL is non-empty and has valid format.
// Returns an error message string if invalid, empty string if valid.
func (c *ServeCommand) validateFeedURL(feedURL string) string {
	if feedURL == "" {
		return "Feed URL cannot be empty"
	}
	if _, err := url.Parse(feedURL); err != nil {
		return "Invalid URL format"
	}
	return ""
}

// renderScanResultsError renders the results template with an error for scan operation.
func (c *ServeCommand) renderScanResultsError(w http.ResponseWriter, errMsg, feedURL string) {
	data := map[string]interface{}{
		"Page":         "tools",
		"IsScanResult": true,
		"Error":        errMsg,
		"FeedURL":      feedURL,
		"PageTitle":    displayTitle(c.Title),
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := c.tmpl.ExecuteTemplate(w, "results", data); err != nil {
		http.Error(w, fmt.Sprintf("Template error: %v", err), http.StatusInternalServerError)
	}
}

func escapeXML(s string) string {
	s = strings.ReplaceAll(s, "&", "&amp;")
	s = strings.ReplaceAll(s, "<", "&lt;")
	s = strings.ReplaceAll(s, ">", "&gt;")
	s = strings.ReplaceAll(s, "\"", "&quot;")
	s = strings.ReplaceAll(s, "'", "&apos;")
	return s
}