summaryrefslogtreecommitdiff
path: root/internal/showcase/showcase.go
blob: 9cf43a637d696205a4d4b3ef113113bbaf9e5875 (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
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
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
package showcase

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"sort"
	"strings"
	"time"

	"codeberg.org/snonux/gitsyncer/internal/config"
)

// Generator handles showcase generation for repositories
type Generator struct {
	config  *config.Config
	workDir string
	aiTool  string
}

// ProjectSummary holds the summary information for a project
type ProjectSummary struct {
	Name         string
	Summary      string
	CodebergURL  string
	GitHubURL    string
	Metadata     *RepoMetadata
	RankHistory  []RepoRankHistory // Latest 5 weekly rank points, newest first
	Images       []string          // Relative paths to images in showcase directory
	CodeSnippet  string            // Code snippet to show when no images
	CodeLanguage string            // Language and file info for the snippet
}

// LegacyRepoMetadata for backwards compatibility with old cache files
type LegacyRepoMetadata struct {
	Languages       []string
	CommitCount     int
	LinesOfCode     int
	FirstCommitDate string
	LastCommitDate  string
	License         string
	AvgCommitAge    float64
}

// New creates a new showcase generator
func New(cfg *config.Config, workDir string) *Generator {
	return &Generator{
		config:  cfg,
		workDir: workDir,
		aiTool:  "opencode", // default to opencode (local Ollama with gpt-oss:120b)
	}
}

// SetAITool sets the AI tool to use for generating summaries
func (g *Generator) SetAITool(tool string) {
	g.aiTool = tool
}

// GenerateShowcase generates a showcase for repositories
// If repoFilter is provided, only those repositories are processed
// If repoFilter is empty/nil, all repositories in work directory are processed
func (g *Generator) GenerateShowcase(repoFilter []string, forceRegenerate bool) error {
	var repos []string
	var err error

	if len(repoFilter) > 0 {
		// Use the provided filter
		repos = repoFilter
	} else {
		// Get all repositories in work directory
		repos, err = g.getRepositories()
		if err != nil {
			return fmt.Errorf("failed to get repositories: %w", err)
		}
	}

	if len(repos) == 0 {
		return fmt.Errorf("no repositories found")
	}

	// Filter out excluded repositories
	filteredRepos := g.filterExcludedRepos(repos)

	fmt.Printf("Found %d repositories to process (after filtering %d excluded)\n",
		len(filteredRepos), len(repos)-len(filteredRepos))

	// Generate summaries for each repository
	summaries := make([]ProjectSummary, 0, len(filteredRepos))
	successCount := 0

	for i, repo := range filteredRepos {
		fmt.Printf("\n[%d/%d] Processing %s...\n", i+1, len(filteredRepos), repo)

		summary, err := g.generateProjectSummary(repo, forceRegenerate)
		if err != nil {
			fmt.Printf("WARNING: Failed to generate summary for %s: %v\n", repo, err)
			continue
		}

		// Print the generated summary to stdout
		fmt.Printf("\n--- Generated summary for %s ---\n", repo)
		fmt.Println(summary.Summary)
		if summary.Metadata != nil {
			fmt.Printf("Languages: %s\n", FormatLanguagesWithPercentages(summary.Metadata.Languages))
			fmt.Printf("Commits: %d\n", summary.Metadata.CommitCount)
			fmt.Printf("Lines of Code: %d\n", summary.Metadata.LinesOfCode)
			fmt.Printf("First Commit: %s\n", summary.Metadata.FirstCommitDate)
			fmt.Printf("Last Commit: %s\n", summary.Metadata.LastCommitDate)
			fmt.Printf("License: %s\n", summary.Metadata.License)
			fmt.Printf("Tags: %d\n", summary.Metadata.TagCount)
			fmt.Printf("Score: %.1f\n", summary.Metadata.Score)
		}
		fmt.Println("--- End of summary ---")

		summaries = append(summaries, *summary)
		successCount++
	}

	if successCount == 0 {
		return fmt.Errorf("failed to generate any summaries")
	}

	fmt.Printf("\nSuccessfully generated %d/%d summaries\n", successCount, len(repos))

	// Sort summaries by score (highest first)
	sort.Slice(summaries, func(i, j int) bool {
		// If metadata is missing, put at the end
		if summaries[i].Metadata == nil {
			return false
		}
		if summaries[j].Metadata == nil {
			return true
		}
		// Higher score is better (combines LOC and recent activity)
		return summaries[i].Metadata.Score > summaries[j].Metadata.Score
	})

	anchorDate := time.Now()
	rankHistoryFile := filepath.Join(g.workDir, rankHistoryFilename)
	rankHistoryStore, err := loadRankHistory(rankHistoryFile)
	if err != nil {
		return fmt.Errorf("failed to load rank history: %w", err)
	}

	// Only full showcase runs should update ranking snapshots.
	if len(repoFilter) == 0 {
		upsertSnapshotForDate(rankHistoryStore, anchorDate, buildCurrentRanks(summaries))
		if err := saveRankHistory(rankHistoryFile, rankHistoryStore); err != nil {
			return fmt.Errorf("failed to save rank history: %w", err)
		}
	}

	applyRankHistoryToSummaries(summaries, rankHistoryStore, anchorDate, rankHistoryPoints)

	// When filtering (single repo), we need to update existing showcase
	if len(repoFilter) > 0 {
		if err := g.updateShowcaseFile(summaries); err != nil {
			return fmt.Errorf("failed to update showcase file: %w", err)
		}
	} else {
		// Full regeneration - format as Gemtext and write
		content := g.formatGemtext(summaries)
		if err := g.writeShowcaseFile(content); err != nil {
			return fmt.Errorf("failed to write showcase file: %w", err)
		}
	}

	return nil
}

// runCommandWithTimeout runs a command with a short timeout and returns trimmed stdout.
// Stderr is included in the error message for easier debugging when GITSYNCER_DEBUG=1.
func runCommandWithTimeout(name string, args ...string) (string, error) {
	return runCommandWithCustomTimeout(8*time.Second, name, args...)
}

func runCommandWithCustomTimeout(timeout time.Duration, name string, args ...string) (string, error) {
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()
	cmd := exec.CommandContext(ctx, name, args...)
	out, err := cmd.CombinedOutput()
	if ctx.Err() == context.DeadlineExceeded {
		return "", fmt.Errorf("command timed out")
	}
	if err != nil {
		// include a snippet of output for debugging
		msg := strings.TrimSpace(string(out))
		if len(msg) > 300 {
			msg = msg[:300] + "..."
		}
		if msg != "" {
			return "", fmt.Errorf("%v: %s", err, msg)
		}
		return "", err
	}
	return string(out), nil
}

func findReadmeContent(repoPath string) ([]byte, string, bool) {
	readmeFiles := []string{
		"README.md", "readme.md", "Readme.md",
		"README.MD", "README.txt", "readme.txt",
		"README", "readme",
	}

	for _, readmeFile := range readmeFiles {
		path := filepath.Join(repoPath, readmeFile)
		content, err := os.ReadFile(path)
		if err == nil {
			return content, readmeFile, true
		}
	}

	return nil, "", false
}

func selectSummaryTool(aiTool string) string {
	switch aiTool {
	case "opencode", "":
		// Default chain: opencode → amp → hexai → claude
		if _, err := exec.LookPath("opencode"); err == nil {
			return "opencode"
		}
		if _, err := exec.LookPath("amp"); err == nil {
			return "amp"
		}
		if _, err := exec.LookPath("hexai"); err == nil {
			return "hexai"
		}
		if _, err := exec.LookPath("claude"); err == nil {
			return "claude"
		}
	case "amp":
		// Explicit amp: amp → hexai → claude
		if _, err := exec.LookPath("amp"); err == nil {
			return "amp"
		}
		if _, err := exec.LookPath("hexai"); err == nil {
			return "hexai"
		}
		if _, err := exec.LookPath("claude"); err == nil {
			return "claude"
		}
	case "claude", "claude-code":
		if _, err := exec.LookPath("claude"); err == nil {
			return "claude"
		}
		if _, err := exec.LookPath("hexai"); err == nil {
			return "hexai"
		}
	case "hexai":
		if _, err := exec.LookPath(aiTool); err == nil {
			return aiTool
		}
	}

	return ""
}

func runSummaryTool(selectedTool, prompt, repoPath, readmeFile string, readmeContent []byte, readmeFound bool) string {
	var cmd *exec.Cmd

	switch selectedTool {
	case "opencode":
		fmt.Printf("Running opencode command (stdin payload)\n")
		if readmeFound {
			fmt.Printf("  echo <README content> | opencode run --model ollama/gpt-oss:120b \"%s\"\n", prompt)
			fmt.Printf("  Using %s as input\n", readmeFile)
			cmd = exec.Command("opencode", "run", "--model", "ollama/gpt-oss:120b", prompt)
			cmd.Stdin = strings.NewReader(string(readmeContent))
		}
	case "amp":
		fmt.Printf("Running amp command (stdin payload)\n")
		if readmeFound {
			fmt.Printf("  echo <README content> | amp --execute \"%s\"\n", prompt)
			fmt.Printf("  Using %s as input\n", readmeFile)
			cmd = exec.Command("amp", "--execute", prompt)
			cmd.Stdin = strings.NewReader(string(readmeContent))
		}
	case "claude":
		fmt.Printf("Running Claude command:\n")
		fmt.Printf("  claude --model sonnet \"%s\"\n", prompt)
		cmd = exec.Command("claude", "--model", "sonnet", prompt)
	case "hexai":
		fmt.Printf("Running hexai command (stdin payload)\n")
		if readmeFound {
			fmt.Printf("  echo <README content> | hexai \"%s\"\n", prompt)
			fmt.Printf("  Using %s as input\n", readmeFile)
			cmd = exec.Command("hexai", prompt)
			cmd.Stdin = strings.NewReader(string(readmeContent))
		}
	}

	if cmd == nil {
		return ""
	}

	cmd.Dir = repoPath
	output, err := cmd.Output()
	if err != nil {
		return ""
	}

	return strings.TrimSpace(string(output))
}

func fallbackSummary(repoName string, readmeContent []byte, readmeFound bool) string {
	if readmeFound {
		if summary := extractUsefulSummary(string(readmeContent), 1); summary != "" {
			return summary
		}
	}

	return fmt.Sprintf("%s: source code repository.", repoName)
}

func extractUsefulSummary(text string, maxParagraphs int) string {
	if maxParagraphs <= 0 {
		maxParagraphs = 1
	}

	parts := splitSummaryParagraphs(text)
	useful := make([]string, 0, maxParagraphs)

	for _, part := range parts {
		part = normalizeSummaryParagraph(part)
		if part == "" {
			continue
		}

		useful = append(useful, part)
		if len(useful) >= maxParagraphs {
			break
		}
	}

	return strings.Join(useful, "\n\n")
}

func normalizeSummaryParagraph(paragraph string) string {
	rawParagraph := strings.TrimSpace(paragraph)
	switch {
	case isHeadingOnlyParagraph(rawParagraph):
		return ""
	case isImageOnlyParagraph(rawParagraph):
		return ""
	case isHTMLOnlyParagraph(rawParagraph):
		return ""
	case isTOCParagraph(rawParagraph):
		return ""
	case isListOnlyParagraph(rawParagraph):
		return ""
	case isBadgeParagraph(rawParagraph):
		return ""
	}

	paragraph = sanitizeSummaryForGemtext(paragraph)
	if paragraph == "" {
		return ""
	}

	if normalized, ok := normalizeManpageParagraph(paragraph); ok {
		paragraph = normalized
	}

	if isLabelOnlyParagraph(paragraph) {
		return ""
	}

	return paragraph
}

func splitSummaryParagraphs(text string) []string {
	text = strings.ReplaceAll(text, "\r\n", "\n")
	text = strings.TrimSpace(text)
	if text == "" {
		return nil
	}

	rawParts := strings.Split(text, "\n\n")
	parts := make([]string, 0, len(rawParts))
	for _, part := range rawParts {
		part = strings.TrimSpace(part)
		if part == "" {
			continue
		}
		parts = append(parts, part)
	}

	return parts
}

func sanitizeSummaryForGemtext(summary string) string {
	summary = strings.ReplaceAll(summary, "\r\n", "\n")
	summary = strings.TrimSpace(summary)
	if summary == "" {
		return ""
	}

	lines := strings.Split(summary, "\n")
	cleaned := make([]string, 0, len(lines))
	inCodeFence := false

	for _, line := range lines {
		trimmed := strings.TrimSpace(line)
		if trimmed == "" {
			if inCodeFence {
				continue
			}
			cleaned = append(cleaned, "")
			continue
		}

		if strings.HasPrefix(trimmed, "```") {
			inCodeFence = !inCodeFence
			continue
		}
		if inCodeFence {
			continue
		}

		if isHTMLOnlyLine(trimmed) || isMarkdownImageLine(trimmed) {
			continue
		}

		if isSetextUnderline(trimmed) && len(cleaned) > 0 && strings.TrimSpace(cleaned[len(cleaned)-1]) != "" {
			continue
		}

		if heading, ok := trimMarkdownHeading(trimmed); ok {
			if heading != "" {
				cleaned = append(cleaned, heading)
			}
			continue
		}

		cleaned = append(cleaned, strings.TrimRight(line, " \t"))
	}

	return strings.TrimSpace(strings.Join(cleaned, "\n"))
}

func isHeadingOnlyParagraph(paragraph string) bool {
	lines := strings.Split(strings.TrimSpace(strings.ReplaceAll(paragraph, "\r\n", "\n")), "\n")
	if len(lines) == 1 {
		_, ok := trimMarkdownHeading(strings.TrimSpace(lines[0]))
		return ok
	}
	if len(lines) == 2 {
		return strings.TrimSpace(lines[0]) != "" && isSetextUnderline(strings.TrimSpace(lines[1]))
	}
	return false
}

func isImageOnlyParagraph(paragraph string) bool {
	trimmed := strings.TrimSpace(paragraph)
	if trimmed == "" || strings.Contains(trimmed, "\n") {
		return false
	}
	return strings.HasPrefix(trimmed, "<img") || strings.HasPrefix(trimmed, "![")
}

func isHTMLOnlyParagraph(paragraph string) bool {
	lines := strings.Split(strings.TrimSpace(paragraph), "\n")
	if len(lines) == 0 {
		return false
	}

	seen := false
	for _, line := range lines {
		trimmed := strings.TrimSpace(line)
		if trimmed == "" {
			continue
		}
		if !isHTMLOnlyLine(trimmed) {
			return false
		}
		seen = true
	}

	return seen
}

func isHTMLOnlyLine(line string) bool {
	return strings.HasPrefix(line, "<") && strings.HasSuffix(line, ">")
}

func isMarkdownImageLine(line string) bool {
	return strings.HasPrefix(line, "![") && strings.Contains(line, "](")
}

func isTOCParagraph(paragraph string) bool {
	lines := strings.Split(strings.TrimSpace(paragraph), "\n")
	if len(lines) == 0 {
		return false
	}

	first := strings.TrimSpace(lines[0])
	if !strings.EqualFold(first, "toc:") && !strings.EqualFold(first, "table of contents:") {
		return false
	}

	for _, line := range lines[1:] {
		trimmed := strings.TrimSpace(line)
		if trimmed == "" {
			continue
		}
		if !isOrderedListLine(trimmed) {
			return false
		}
	}

	return true
}

func isListOnlyParagraph(paragraph string) bool {
	lines := strings.Split(strings.TrimSpace(paragraph), "\n")
	if len(lines) == 0 {
		return false
	}

	seen := false
	for _, line := range lines {
		trimmed := strings.TrimSpace(line)
		if trimmed == "" {
			continue
		}
		if !isListLine(trimmed) {
			return false
		}
		seen = true
	}

	return seen
}

func isListLine(line string) bool {
	return strings.HasPrefix(line, "* ") || strings.HasPrefix(line, "- ") || isOrderedListLine(line)
}

func isOrderedListLine(line string) bool {
	if line == "" || line[0] < '0' || line[0] > '9' {
		return false
	}

	i := 0
	for i < len(line) && line[i] >= '0' && line[i] <= '9' {
		i++
	}
	if i == 0 || i >= len(line) {
		return false
	}
	if (line[i] != '.' && line[i] != ')') || i+1 >= len(line) || line[i+1] != ' ' {
		return false
	}

	return true
}

func isLabelOnlyParagraph(paragraph string) bool {
	lines := strings.Split(strings.TrimSpace(paragraph), "\n")
	if len(lines) != 1 {
		return false
	}

	line := strings.TrimSpace(lines[0])
	if line == "" {
		return false
	}
	if strings.HasSuffix(line, ":") && len(strings.Fields(line)) <= 5 {
		return true
	}

	return line == strings.ToUpper(line) && len(strings.Fields(line)) <= 4
}

func isBadgeParagraph(paragraph string) bool {
	lines := strings.Split(strings.TrimSpace(paragraph), "\n")
	if len(lines) != 1 {
		return false
	}

	line := strings.TrimSpace(lines[0])
	if line == "" {
		return false
	}

	markerCount := strings.Count(line, "](") + strings.Count(line, "![")
	return markerCount >= 2
}

func normalizeManpageParagraph(paragraph string) (string, bool) {
	lines := strings.Split(strings.TrimSpace(paragraph), "\n")
	if len(lines) < 2 {
		return "", false
	}
	if strings.TrimSpace(lines[0]) != "NAME" {
		return "", false
	}

	body := make([]string, 0, len(lines)-1)
	for _, line := range lines[1:] {
		trimmed := strings.TrimSpace(line)
		if trimmed == "" {
			continue
		}
		body = append(body, trimmed)
	}
	if len(body) == 0 {
		return "", false
	}

	return strings.Join(body, " "), true
}

func trimMarkdownHeading(line string) (string, bool) {
	if line == "" || !strings.HasPrefix(line, "#") {
		return "", false
	}

	level := 0
	for level < len(line) && line[level] == '#' {
		level++
	}
	if level == 0 || level > 6 {
		return "", false
	}
	if level < len(line) && line[level] != ' ' && line[level] != '\t' {
		return "", false
	}

	heading := strings.TrimSpace(line[level:])
	heading = strings.TrimSpace(strings.TrimRight(heading, "#"))
	return heading, true
}

func isSetextUnderline(line string) bool {
	if len(line) < 3 {
		return false
	}
	return strings.Trim(line, "=") == "" || strings.Trim(line, "-") == ""
}

// getRepositories returns a list of repository directories in the work directory
func (g *Generator) getRepositories() ([]string, error) {
	entries, err := os.ReadDir(g.workDir)
	if err != nil {
		return nil, err
	}

	var repos []string
	for _, entry := range entries {
		if !entry.IsDir() {
			continue
		}

		// Check if it's a git repository
		gitDir := filepath.Join(g.workDir, entry.Name(), ".git")
		if info, err := os.Stat(gitDir); err == nil && info.IsDir() {
			repos = append(repos, entry.Name())
		}
	}

	// Sort repositories alphabetically
	sort.Strings(repos)
	return repos, nil
}

func (g *Generator) buildProjectLinks(repoName string) (string, string) {
	codebergURL := ""
	githubURL := ""

	if codebergOrg := g.config.FindCodebergOrg(); codebergOrg != nil {
		codebergURL = fmt.Sprintf("https://codeberg.org/%s/%s", codebergOrg.Name, repoName)
	}

	if githubOrg := g.config.FindGitHubOrg(); githubOrg != nil {
		githubURL = fmt.Sprintf("https://github.com/%s/%s", githubOrg.Name, repoName)
	}

	return codebergURL, githubURL
}

func (g *Generator) prepareStatsRepoPath(repoName, repoPath string) (string, func() error, error) {
	if g.config == nil {
		return repoPath, func() error { return nil }, nil
	}

	branch := strings.TrimSpace(g.config.ShowcaseStatsBranches[repoName])
	if branch == "" {
		return repoPath, func() error { return nil }, nil
	}

	resolvedRef, err := resolveShowcaseStatsRef(repoPath, branch)
	if err != nil {
		return "", nil, fmt.Errorf("failed to resolve showcase stats branch for %s: %w", repoName, err)
	}

	tempPrefix := strings.ReplaceAll(repoName, string(os.PathSeparator), "-")
	tempRoot, err := os.MkdirTemp("", "gitsyncer-showcase-"+tempPrefix+"-")
	if err != nil {
		return "", nil, fmt.Errorf("failed to create temporary worktree root for %s: %w", repoName, err)
	}

	worktreePath := filepath.Join(tempRoot, "repo")
	if _, err := runCommandWithCustomTimeout(45*time.Second, "git", "-C", repoPath, "worktree", "add", "--detach", worktreePath, resolvedRef); err != nil {
		_ = os.RemoveAll(tempRoot)
		return "", nil, fmt.Errorf("failed to create showcase stats worktree for %s on branch %q: %w", repoName, branch, err)
	}

	cleanup := func() error {
		defer os.RemoveAll(tempRoot)

		if _, err := runCommandWithCustomTimeout(45*time.Second, "git", "-C", repoPath, "worktree", "remove", "--force", worktreePath); err != nil {
			return fmt.Errorf("failed to remove temporary worktree for %s: %w", repoName, err)
		}

		return nil
	}

	if resolvedRef == branch {
		fmt.Printf("Using showcase stats branch %q for %s\n", branch, repoName)
	} else {
		fmt.Printf("Using showcase stats branch %q for %s (resolved to %s)\n", branch, repoName, resolvedRef)
	}

	return worktreePath, cleanup, nil
}

func resolveShowcaseStatsRef(repoPath, branch string) (string, error) {
	localRef := "refs/heads/" + branch
	if _, err := runCommandWithTimeout("git", "-C", repoPath, "show-ref", "--verify", "--quiet", localRef); err == nil {
		return branch, nil
	}

	output, err := runCommandWithTimeout("git", "-C", repoPath, "for-each-ref", "--format=%(refname)", "refs/remotes")
	if err != nil {
		return "", fmt.Errorf("failed to inspect remote refs for branch %q: %w", branch, err)
	}

	var candidates []string
	for _, line := range strings.Split(strings.TrimSpace(output), "\n") {
		ref := strings.TrimSpace(line)
		if ref == "" || strings.HasSuffix(ref, "/HEAD") {
			continue
		}
		if strings.HasSuffix(ref, "/"+branch) {
			candidates = append(candidates, ref)
		}
	}

	if len(candidates) == 0 {
		return "", fmt.Errorf("branch %q not found locally or on any remote", branch)
	}

	sort.Strings(candidates)
	for _, ref := range candidates {
		if strings.HasPrefix(ref, "refs/remotes/origin/") {
			return ref, nil
		}
	}

	return candidates[0], nil
}

// generateProjectSummary generates a summary for a single project
func (g *Generator) generateProjectSummary(repoName string, forceRegenerate bool) (*ProjectSummary, error) {
	repoPath := filepath.Join(g.workDir, repoName)

	// Check cache first
	cacheDir := filepath.Join(g.workDir, ".gitsyncer-showcase-cache")
	cacheFile := filepath.Join(cacheDir, repoName+".json")

	// Try to load cached summary (but we'll still update metadata and images)
	var cachedSummary string
	var haveCachedSummary bool
	if !forceRegenerate {
		if cached, err := g.loadFromCache(cacheFile); err == nil {
			fmt.Printf("Using cached AI summary (cache file: %s)\n", cacheFile)
			cachedSummary = cached.Summary
			haveCachedSummary = true
		}
	}

	// Determine which AI tool to use (only if we need to run it)
	// Prefer amp if available when default tool is "" (aligns with release flow)
	selectedTool := g.aiTool
	if !haveCachedSummary {
		selectedTool = selectSummaryTool(g.aiTool)
	}

	readmeContent, readmeFile, readmeFound := findReadmeContent(repoPath)

	statsRepoPath, cleanupStatsRepoPath, err := g.prepareStatsRepoPath(repoName, repoPath)
	if err != nil {
		return nil, err
	}
	defer func() {
		if err := cleanupStatsRepoPath(); err != nil {
			fmt.Printf("Warning: %v\n", err)
		}
	}()

	// Always extract metadata (not cached)
	fmt.Printf("Extracting repository metadata...\n")
	metadata, err := extractRepoMetadata(statsRepoPath)
	if err != nil {
		fmt.Printf("Warning: Failed to extract some metadata: %v\n", err)
		// Continue anyway with partial metadata
	}

	// Get the summary - either from cache or by running AI tool
	var summary string
	if haveCachedSummary {
		summary = cachedSummary
		fmt.Printf("Using cached AI summary\n")
	} else {
		prompt := "Please provide a 1-2 paragraph summary of this project, explaining what it does, why it's useful, and how it's implemented. Focus on the key features and architecture. Be concise but informative."
		summary = runSummaryTool(selectedTool, prompt, repoPath, readmeFile, readmeContent, readmeFound)

		// Fallback: create a minimal summary from README if AI unavailable/failed
		if summary == "" {
			summary = fallbackSummary(repoName, readmeContent, readmeFound)
		}
	}
	summary = extractUsefulSummary(summary, 2)
	if summary == "" {
		summary = fallbackSummary(repoName, readmeContent, readmeFound)
	}
	summary = sanitizeSummaryForGemtext(summary)

	// Build URLs
	codebergURL, githubURL := g.buildProjectLinks(repoName)

	// Always extract images from README (not cached)
	fmt.Printf("Extracting images from README...\n")
	home, err := os.UserHomeDir()
	if err != nil {
		return nil, fmt.Errorf("failed to get home directory: %w", err)
	}
	showcaseDir := filepath.Join(home, "git", "foo.zone-content", "gemtext", "about")
	images, err := extractImagesFromRepo(repoPath, repoName, showcaseDir)
	if err != nil {
		fmt.Printf("Warning: Failed to extract images: %v\n", err)
		// Continue without images
	}

	// Extract code snippet for all projects
	var codeSnippet, codeLanguage string
	if metadata != nil && len(metadata.Languages) > 0 {
		snippet, lang, err := extractCodeSnippet(statsRepoPath, metadata.Languages)
		if err != nil {
			fmt.Printf("Warning: Failed to extract code snippet: %v\n", err)
		} else {
			codeSnippet = snippet
			codeLanguage = lang
		}
	}

	projectSummary := &ProjectSummary{
		Name:         repoName,
		Summary:      summary,
		CodebergURL:  codebergURL,
		GitHubURL:    githubURL,
		Metadata:     metadata,
		Images:       images,
		CodeSnippet:  codeSnippet,
		CodeLanguage: codeLanguage,
	}

	// Save to cache
	if err := g.saveToCache(cacheFile, projectSummary); err != nil {
		fmt.Printf("Warning: Failed to save to cache: %v\n", err)
	} else {
		fmt.Printf("Summary cached at: %s\n", cacheFile)
	}

	return projectSummary, nil
}

// formatGemtext formats the summaries as Gemini Gemtext
func (g *Generator) formatGemtext(summaries []ProjectSummary) string {
	var builder strings.Builder

	// Header
	builder.WriteString("# Project Showcase\n\n")

	// Generated date at the top
	builder.WriteString(fmt.Sprintf("Generated on: %s\n\n", time.Now().Format("2006-01-02")))

	// Introduction paragraph
	builder.WriteString("This page showcases my side projects, providing an overview of what each project does, its technical implementation, and key metrics. Each project summary includes information about the programming languages used, development activity, releases, and licensing. The projects are ranked by score, which combines recent activity, project size, tag history, and whether the project has shipped a release.\n\n")

	// Template inline TOC
	builder.WriteString("<< template::inline::toc\n\n")

	// Calculate total stats
	totalProjects := len(summaries)
	totalCommits := 0
	totalLOC := 0
	totalDocs := 0
	releasedCount := 0
	languageTotals := make(map[string]int)
	docTotals := make(map[string]int)

	for _, summary := range summaries {
		if summary.Metadata != nil {
			totalCommits += summary.Metadata.CommitCount
			totalLOC += summary.Metadata.LinesOfCode
			totalDocs += summary.Metadata.LinesOfDocs

			// Count projects with releases
			if summary.Metadata.HasReleases {
				releasedCount++
			}

			// Aggregate language statistics
			for _, lang := range summary.Metadata.Languages {
				languageTotals[lang.Name] += lang.Lines
			}

			// Aggregate documentation statistics
			for _, doc := range summary.Metadata.Documentation {
				docTotals[doc.Name] += doc.Lines
			}
		}
	}

	// Calculate language percentages
	var languageStats []LanguageStats
	for name, lines := range languageTotals {
		percentage := 0.0
		if totalLOC > 0 {
			percentage = float64(lines) * 100.0 / float64(totalLOC)
		}
		languageStats = append(languageStats, LanguageStats{
			Name:       name,
			Lines:      lines,
			Percentage: percentage,
		})
	}

	// Sort languages by percentage
	sort.Slice(languageStats, func(i, j int) bool {
		return languageStats[i].Percentage > languageStats[j].Percentage
	})

	// Calculate documentation percentages
	var docStats []LanguageStats
	for name, lines := range docTotals {
		percentage := 0.0
		if totalDocs > 0 {
			percentage = float64(lines) * 100.0 / float64(totalDocs)
		}
		docStats = append(docStats, LanguageStats{
			Name:       name,
			Lines:      lines,
			Percentage: percentage,
		})
	}

	// Sort documentation by percentage
	sort.Slice(docStats, func(i, j int) bool {
		return docStats[i].Percentage > docStats[j].Percentage
	})

	// Write total stats section
	builder.WriteString("## Overall Statistics\n\n")
	builder.WriteString(fmt.Sprintf("* 📦 Total Projects: %d\n", totalProjects))
	builder.WriteString(fmt.Sprintf("* 📊 Total Commits: %s\n", formatNumber(totalCommits)))
	builder.WriteString(fmt.Sprintf("* 📈 Total Lines of Code: %s\n", formatNumber(totalLOC)))
	if totalDocs > 0 {
		builder.WriteString(fmt.Sprintf("* 📄 Total Lines of Documentation: %s\n", formatNumber(totalDocs)))
	}
	if len(languageStats) > 0 {
		builder.WriteString(fmt.Sprintf("* 💻 Languages: %s\n", FormatLanguagesWithPercentages(languageStats)))
	}
	if len(docStats) > 0 {
		builder.WriteString(fmt.Sprintf("* 📚 Documentation: %s\n", FormatLanguagesWithPercentages(docStats)))
	}
	experimentalCount := totalProjects - releasedCount
	builder.WriteString(fmt.Sprintf("* 🚀 Release Status: %d released, %d experimental (%.1f%% with releases, %.1f%% experimental)\n",
		releasedCount, experimentalCount,
		float64(releasedCount)*100/float64(totalProjects),
		float64(experimentalCount)*100/float64(totalProjects)))
	builder.WriteString("\n")

	// Add Projects section
	builder.WriteString("## Projects\n\n")

	// Add each project
	for i, summary := range summaries {
		if i > 0 {
			builder.WriteString("\n---\n\n")
		}

		builder.WriteString(fmt.Sprintf("### %d. %s%s\n\n", i+1, summary.Name, formatRankHistoryForHeader(summary.RankHistory)))

		// Add metadata if available
		if summary.Metadata != nil {
			if len(summary.Metadata.Languages) > 0 {
				builder.WriteString(fmt.Sprintf("* 💻 Languages: %s\n", FormatLanguagesWithPercentages(summary.Metadata.Languages)))
			}
			if len(summary.Metadata.Documentation) > 0 {
				builder.WriteString(fmt.Sprintf("* 📚 Documentation: %s\n", FormatLanguagesWithPercentages(summary.Metadata.Documentation)))
			}
			builder.WriteString(fmt.Sprintf("* 📊 Commits: %d\n", summary.Metadata.CommitCount))
			builder.WriteString(fmt.Sprintf("* 📈 Lines of Code: %d\n", summary.Metadata.LinesOfCode))
			if summary.Metadata.LinesOfDocs > 0 {
				builder.WriteString(fmt.Sprintf("* 📄 Lines of Documentation: %d\n", summary.Metadata.LinesOfDocs))
			}
			builder.WriteString(fmt.Sprintf("* 🏷️ Tags: %d\n", summary.Metadata.TagCount))
			builder.WriteString(fmt.Sprintf("* 📅 Development Period: %s to %s\n", summary.Metadata.FirstCommitDate, summary.Metadata.LastCommitDate))
			builder.WriteString(fmt.Sprintf("* 🏆 Score: %.1f (combines recent activity, code size, tags, and release status)\n", summary.Metadata.Score))
			builder.WriteString(fmt.Sprintf("* ⚖️ License: %s\n", summary.Metadata.License))

			// Add release information or experimental status
			if summary.Metadata.HasReleases && summary.Metadata.LatestTag != "" {
				if summary.Metadata.LatestTagDate != "" {
					builder.WriteString(fmt.Sprintf("* 🏷️ Latest Release: %s (%s)\n", summary.Metadata.LatestTag, summary.Metadata.LatestTagDate))
				} else {
					builder.WriteString(fmt.Sprintf("* 🏷️ Latest Release: %s\n", summary.Metadata.LatestTag))
				}
			} else {
				builder.WriteString("* 🧪 Status: Experimental (no releases yet)\n")
			}

			// Check if project might be obsolete (avg age > 2 years AND last commit > 1 year)
			if summary.Metadata.AvgCommitAge > 730 && summary.Metadata.LastCommitDate != "" {
				// Parse the last commit date
				lastCommit, err := time.Parse("2006-01-02", summary.Metadata.LastCommitDate)
				if err == nil {
					daysSinceLastCommit := time.Since(lastCommit).Hours() / 24
					if daysSinceLastCommit > 365 {
						builder.WriteString("\n⚠️  **Notice**: This project appears to be finished, obsolete, or no longer maintained. Last meaningful activity was over 2 years ago. Use at your own risk.")
					}
				}
			}
			builder.WriteString("\n\n")
		}

		// Handle images and paragraphs
		paragraphs := splitSummaryParagraphs(sanitizeSummaryForGemtext(summary.Summary))

		// If we have images, distribute them nicely
		if len(summary.Images) > 0 {
			// First image after metadata, before text
			builder.WriteString(fmt.Sprintf("=> %s %s screenshot\n\n", summary.Images[0], summary.Name))

			// First paragraph
			if len(paragraphs) > 0 {
				builder.WriteString(fmt.Sprintf("%s\n\n", strings.TrimSpace(paragraphs[0])))
			}

			// Second image after first paragraph (if we have 2 images and multiple paragraphs)
			if len(summary.Images) > 1 && len(paragraphs) > 1 {
				builder.WriteString(fmt.Sprintf("=> %s %s screenshot\n\n", summary.Images[1], summary.Name))
			}

			// Remaining paragraphs
			for i := 1; i < len(paragraphs); i++ {
				builder.WriteString(fmt.Sprintf("%s\n\n", strings.TrimSpace(paragraphs[i])))
			}
		} else {
			// No images - just add all paragraphs
			for _, para := range paragraphs {
				builder.WriteString(fmt.Sprintf("%s\n\n", strings.TrimSpace(para)))
			}
		}

		// Add links
		if summary.CodebergURL != "" {
			builder.WriteString(fmt.Sprintf("=> %s View on Codeberg\n", summary.CodebergURL))
		}
		if summary.GitHubURL != "" {
			builder.WriteString(fmt.Sprintf("=> %s View on GitHub\n", summary.GitHubURL))
		}

	}

	return builder.String()
}

// writeShowcaseFile writes the showcase content to the target file
func (g *Generator) writeShowcaseFile(content string) error {
	// Build target path
	home, err := os.UserHomeDir()
	if err != nil {
		return fmt.Errorf("failed to get home directory: %w", err)
	}

	targetDir := filepath.Join(home, "git", "foo.zone-content", "gemtext", "about")
	targetFile := filepath.Join(targetDir, "showcase.gmi.tpl")

	// Create directory if it doesn't exist
	if err := os.MkdirAll(targetDir, 0755); err != nil {
		return fmt.Errorf("failed to create directory %s: %w", targetDir, err)
	}

	// Write file
	if err := os.WriteFile(targetFile, []byte(content), 0644); err != nil {
		return fmt.Errorf("failed to write file: %w", err)
	}

	fmt.Printf("\nShowcase written to: %s\n", targetFile)
	return nil
}

// updateShowcaseFile updates specific entries in an existing showcase file
func (g *Generator) updateShowcaseFile(newSummaries []ProjectSummary) error {
	// Load existing summaries from cache files instead of parsing Gemtext
	existingSummaries := make(map[string]ProjectSummary)

	// Get all repositories in work directory to load their cached summaries
	repos, err := g.getRepositories()
	if err == nil {
		cacheDir := filepath.Join(g.workDir, ".gitsyncer-showcase-cache")
		for _, repo := range repos {
			// Skip excluded repos
			if g.isExcluded(repo) {
				continue
			}

			cacheFile := filepath.Join(cacheDir, repo+".json")
			if cached, err := g.loadFromCache(cacheFile); err == nil {
				existingSummaries[repo] = *cached
			}
		}
	}

	// Update with new summaries
	for _, summary := range newSummaries {
		existingSummaries[summary.Name] = summary
	}

	// Convert map to slice
	var allSummaries []ProjectSummary
	for _, summary := range existingSummaries {
		allSummaries = append(allSummaries, summary)
	}

	// Sort by score (highest first)
	sort.Slice(allSummaries, func(i, j int) bool {
		// If metadata is missing, put at the end
		if allSummaries[i].Metadata == nil {
			return false
		}
		if allSummaries[j].Metadata == nil {
			return true
		}
		// Higher score is better (combines LOC and recent activity)
		return allSummaries[i].Metadata.Score > allSummaries[j].Metadata.Score
	})

	rankHistoryFile := filepath.Join(g.workDir, rankHistoryFilename)
	rankHistoryStore, err := loadRankHistory(rankHistoryFile)
	if err != nil {
		return fmt.Errorf("failed to load rank history: %w", err)
	}
	applyRankHistoryToSummaries(allSummaries, rankHistoryStore, time.Now(), rankHistoryPoints)

	// Format and write
	content := g.formatGemtext(allSummaries)
	if err := g.writeShowcaseFile(content); err != nil {
		return err
	}

	return nil
}

// loadFromCache loads a project summary from cache
func (g *Generator) loadFromCache(cacheFile string) (*ProjectSummary, error) {
	data, err := os.ReadFile(cacheFile)
	if err != nil {
		return nil, err
	}

	var summary ProjectSummary
	if err := json.Unmarshal(data, &summary); err != nil {
		return nil, err
	}

	return &summary, nil
}

// saveToCache saves a project summary to cache
func (g *Generator) saveToCache(cacheFile string, summary *ProjectSummary) error {
	// Create cache directory if it doesn't exist
	cacheDir := filepath.Dir(cacheFile)
	if err := os.MkdirAll(cacheDir, 0755); err != nil {
		return err
	}

	// Marshal to JSON
	data, err := json.MarshalIndent(summary, "", "  ")
	if err != nil {
		return err
	}

	// Write to file
	return os.WriteFile(cacheFile, data, 0644)
}

// verifyImages checks if cached images still exist
func (g *Generator) verifyImages(summary *ProjectSummary) error {
	if len(summary.Images) == 0 {
		return nil
	}

	home, err := os.UserHomeDir()
	if err != nil {
		return err
	}

	showcaseDir := filepath.Join(home, "git", "foo.zone-content", "gemtext", "about")

	for _, imgPath := range summary.Images {
		fullPath := filepath.Join(showcaseDir, imgPath)
		if _, err := os.Stat(fullPath); err != nil {
			return fmt.Errorf("image not found: %s", imgPath)
		}
	}

	return nil
}

// filterExcludedRepos filters out repositories that are in the exclusion list
func (g *Generator) filterExcludedRepos(repos []string) []string {
	// Filter repositories
	var filtered []string
	for _, repo := range repos {
		if !g.isExcluded(repo) {
			filtered = append(filtered, repo)
		} else {
			fmt.Printf("Excluding repository from showcase (%s): %s\n", g.exclusionReason(repo), repo)
		}
	}

	return filtered
}

// isExcluded checks if a repository is in the exclusion list
func (g *Generator) isExcluded(repo string) bool {
	if isBackupRepo(repo) {
		return true
	}

	for _, excluded := range g.config.ExcludeFromShowcase {
		if excluded == repo {
			return true
		}
	}
	return false
}

// exclusionReason returns why a repository is excluded from showcase generation.
func (g *Generator) exclusionReason(repo string) string {
	var reasons []string

	if isBackupRepo(repo) {
		reasons = append(reasons, "backup suffix")
	}

	for _, excluded := range g.config.ExcludeFromShowcase {
		if excluded == repo {
			reasons = append(reasons, "config")
			break
		}
	}

	if len(reasons) == 0 {
		return "unknown reason"
	}

	return strings.Join(reasons, ", ")
}

// isBackupRepo checks whether a repository name has a backup suffix.
// Excluded patterns: *.bak and *.bak.*
func isBackupRepo(repo string) bool {
	return strings.HasSuffix(repo, ".bak") || strings.Contains(repo, ".bak.")
}

// formatNumber formats a number with thousands separators
func formatNumber(n int) string {
	str := fmt.Sprintf("%d", n)
	if len(str) <= 3 {
		return str
	}

	// Insert commas from right to left
	var result []byte
	for i := len(str) - 1; i >= 0; i-- {
		if (len(str)-i-1) > 0 && (len(str)-i-1)%3 == 0 {
			result = append([]byte{','}, result...)
		}
		result = append([]byte{str[i]}, result...)
	}

	return string(result)
}