Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
import-bulk.tsx30.8 KB · 1011 lines
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
/**
 * Bulk GitHub import — "paste my org + token → import everything".
 *
 * Owner flow for migrating many products at once. Reuses the single-repo
 * import logic from `src/lib/import-helper.ts` so the clone + DB insert
 * code path is identical to `/import`.
 *
 * Token never leaves this process: it's read from the form body, passed
 * to GitHub's API via `Authorization` header, and embedded in the git
 * clone URL only at the moment of spawning `git`. Results never contain
 * the token — `scrubSecrets()` in the helper redacts it before display.
 */

import { Hono } from "hono";
import { Layout } from "../views/layout";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import {
  sanitizeRepoName,
  importOneRepo,
  type ImportOneRepoResult,
} from "../lib/import-helper";

const importBulkRoutes = new Hono<AuthEnv>();

importBulkRoutes.use("*", softAuth);

// Hard limits to keep a single request bounded.
const MAX_REPOS = 200;
const MAX_REPO_SIZE_KB = 500 * 1024; // 500 MB in KB (GitHub reports size in KB)
const GITHUB_PER_PAGE = 100;

interface GitHubRepo {
  name: string;
  full_name: string;
  description: string | null;
  private: boolean;
  clone_url: string;
  default_branch: string;
  fork: boolean;
  size: number; // KB
}

type Visibility = "public" | "private" | "both";

// ─── PAGE-SCOPED CSS ─────────────────────────────────────────
// All classes prefixed with .import-bulk- so the block cannot bleed
// into neighbouring routes. Mirrors the /import polish.
const importBulkStyles = `
  .import-bulk-container { max-width: 880px; margin: 0 auto; }

  /* ─── Hero ─── */
  .import-bulk-hero {
    position: relative;
    margin-bottom: var(--space-6);
    padding: var(--space-5) var(--space-6);
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 16px;
    overflow: hidden;
  }
  .import-bulk-hero::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent 0%, #8c6dff 30%, #36c5d6 70%, transparent 100%);
    opacity: 0.75;
    pointer-events: none;
  }
  .import-bulk-hero-bg {
    position: absolute;
    inset: -20% -10% auto auto;
    width: 360px; height: 360px;
    pointer-events: none;
    z-index: 0;
  }
  .import-bulk-hero-orb {
    position: absolute;
    inset: 0;
    background: radial-gradient(circle, rgba(140,109,255,0.20), rgba(54,197,214,0.10) 45%, transparent 70%);
    filter: blur(80px);
    opacity: 0.7;
    animation: importBulkHeroOrb 14s ease-in-out infinite;
  }
  @keyframes importBulkHeroOrb {
    0%, 100% { transform: scale(1) translate(0, 0); opacity: 0.6; }
    50%      { transform: scale(1.1) translate(-10px, 8px); opacity: 0.85; }
  }
  @media (prefers-reduced-motion: reduce) {
    .import-bulk-hero-orb { animation: none; }
  }
  .import-bulk-hero-inner {
    position: relative;
    z-index: 1;
    max-width: 640px;
  }
  .import-bulk-hero-eyebrow {
    font-size: 13px;
    color: var(--text-muted);
    margin-bottom: var(--space-2);
    letter-spacing: -0.005em;
  }
  .import-bulk-hero-eyebrow-dot {
    display: inline-block;
    width: 6px; height: 6px;
    border-radius: 50%;
    background: var(--accent);
    box-shadow: 0 0 8px rgba(140,109,255,0.6);
    margin-right: 8px;
    vertical-align: 1px;
  }
  .import-bulk-hero-title {
    font-size: clamp(28px, 4vw, 40px);
    font-family: var(--font-display);
    font-weight: 800;
    letter-spacing: -0.028em;
    line-height: 1.05;
    margin: 0 0 var(--space-2);
    color: var(--text-strong);
  }
  .import-bulk-hero-title .gradient-text {
    background-image: linear-gradient(135deg, #a48bff 0%, #8c6dff 50%, #36c5d6 100%);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    color: transparent;
  }
  .import-bulk-hero-sub {
    font-size: 15px;
    color: var(--text-muted);
    margin: 0;
    line-height: 1.55;
  }

  /* ─── Banners ─── */
  .import-bulk-banner {
    position: relative;
    padding: 14px 16px 14px 44px;
    margin-bottom: var(--space-5);
    border-radius: 12px;
    border: 1px solid var(--border);
    background: var(--bg-elevated);
    font-size: 14px;
    line-height: 1.5;
  }
  .import-bulk-banner::before {
    content: '';
    position: absolute;
    left: 14px; top: 18px;
    width: 14px; height: 14px;
    border-radius: 50%;
  }
  .import-bulk-banner-error {
    border-color: rgba(248, 81, 73, 0.32);
    background: linear-gradient(180deg, rgba(248,81,73,0.06) 0%, var(--bg-elevated) 100%);
  }
  .import-bulk-banner-error::before {
    background: radial-gradient(circle, #f85149 30%, transparent 70%);
    box-shadow: 0 0 10px rgba(248,81,73,0.5);
  }
  .import-bulk-banner-title { font-weight: 600; color: var(--text-strong); }
  .import-bulk-banner-detail { color: var(--text-muted); margin-top: 4px; font-size: 13.5px; }

  /* ─── Section cards ─── */
  .import-bulk-section {
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 14px;
    margin-bottom: var(--space-5);
    overflow: hidden;
  }
  .import-bulk-section-head {
    padding: var(--space-4) var(--space-5) var(--space-3);
    border-bottom: 1px solid var(--border);
  }
  .import-bulk-section-eyebrow {
    font-size: 11px;
    font-weight: 600;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: var(--accent);
    margin-bottom: 6px;
  }
  .import-bulk-section-title {
    font-family: var(--font-display);
    font-size: 18px;
    font-weight: 700;
    letter-spacing: -0.018em;
    margin: 0 0 4px;
    color: var(--text-strong);
  }
  .import-bulk-section-desc {
    font-size: 13.5px;
    color: var(--text-muted);
    margin: 0;
    line-height: 1.5;
  }
  .import-bulk-section-body { padding: var(--space-4) var(--space-5); }

  /* ─── Form ─── */
  .import-bulk-field { margin-bottom: var(--space-4); }
  .import-bulk-field:last-child { margin-bottom: 0; }
  .import-bulk-field-label {
    display: block;
    font-size: 13px;
    font-weight: 600;
    color: var(--text-strong);
    margin-bottom: 6px;
    letter-spacing: -0.005em;
  }
  .import-bulk-field-label code {
    font-size: 12px;
    background: var(--bg-tertiary, var(--bg-secondary));
    padding: 1px 5px;
    border-radius: 4px;
    font-weight: 500;
    color: var(--text-muted);
  }
  .import-bulk-input,
  .import-bulk-select {
    width: 100%;
    padding: 9px 12px;
    font-size: 14px;
    color: var(--text);
    background: var(--bg);
    border: 1px solid var(--border-strong);
    border-radius: 8px;
    outline: none;
    transition: border-color 120ms ease, box-shadow 120ms ease;
    font-family: var(--font-sans);
  }
  .import-bulk-input.is-mono { font-family: var(--font-mono); font-size: 13px; }
  .import-bulk-input:focus,
  .import-bulk-select:focus {
    border-color: var(--accent);
    box-shadow: 0 0 0 3px rgba(140,109,255,0.18);
  }

  /* ─── Toggle row (dry-run checkbox) ─── */
  .import-bulk-toggle {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 12px 14px;
    border-radius: 10px;
    border: 1px solid var(--border-subtle);
    background: var(--bg-secondary);
    transition: border-color 120ms ease;
  }
  .import-bulk-toggle:hover { border-color: var(--border); }
  .import-bulk-toggle input[type="checkbox"] {
    margin-top: 2px;
    width: 16px; height: 16px;
    accent-color: var(--accent);
    cursor: pointer;
  }
  .import-bulk-toggle-text {
    font-size: 13.5px;
    color: var(--text);
    line-height: 1.45;
  }
  .import-bulk-toggle-hint {
    display: block;
    margin-top: 3px;
    font-size: 12.5px;
    color: var(--text-muted);
  }

  .import-bulk-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    align-items: center;
    margin-top: var(--space-4);
  }

  /* ─── Info / "what this does" panel ─── */
  .import-bulk-info {
    position: relative;
    padding: 14px 16px 14px 18px;
    margin-bottom: var(--space-5);
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 12px;
    overflow: hidden;
  }
  .import-bulk-info::before {
    content: '';
    position: absolute;
    left: 0; top: 0; bottom: 0;
    width: 3px;
    background: linear-gradient(180deg, #8c6dff 0%, #36c5d6 100%);
  }
  .import-bulk-info strong {
    display: block;
    font-family: var(--font-display);
    font-weight: 700;
    font-size: 14px;
    color: var(--text-strong);
    letter-spacing: -0.012em;
    margin-bottom: 6px;
  }
  .import-bulk-info ul {
    margin: 0;
    padding-left: 18px;
    font-size: 13px;
    color: var(--text-muted);
    line-height: 1.6;
  }
  .import-bulk-info code {
    font-size: 12px;
    background: var(--bg-secondary);
    padding: 1px 5px;
    border-radius: 4px;
    color: var(--text);
  }

  /* ─── Summary strip (counts) ─── */
  .import-bulk-summary {
    display: flex;
    align-items: center;
    gap: var(--space-3);
    flex-wrap: wrap;
    padding: 12px 16px;
    margin-bottom: var(--space-4);
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 12px;
    font-size: 13.5px;
    color: var(--text-muted);
  }
  .import-bulk-summary code {
    font-size: 12.5px;
    background: var(--bg-secondary);
    padding: 1px 6px;
    border-radius: 4px;
    color: var(--text);
  }
  .import-bulk-summary-stat {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 3px 10px;
    border-radius: 9999px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-subtle);
    font-weight: 500;
    color: var(--text-strong);
    font-size: 12.5px;
  }
  .import-bulk-summary-stat .num { color: var(--accent); font-weight: 700; }

  /* ─── Results table ─── */
  .import-bulk-table-wrap {
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 14px;
    overflow: hidden;
  }
  .import-bulk-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13.5px;
  }
  .import-bulk-table thead tr {
    background: var(--bg-secondary);
    text-align: left;
  }
  .import-bulk-table th {
    padding: 10px 14px;
    border-bottom: 1px solid var(--border);
    font-size: 11.5px;
    font-weight: 600;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    color: var(--text-muted);
  }
  .import-bulk-table tbody tr {
    transition: background 120ms ease;
  }
  .import-bulk-table tbody tr:hover {
    background: rgba(255,255,255,0.018);
  }
  .import-bulk-table td {
    padding: 9px 14px;
    border-bottom: 1px solid var(--border-subtle);
    vertical-align: middle;
  }
  .import-bulk-table tbody tr:last-child td { border-bottom: 0; }
  .import-bulk-table-name {
    font-family: var(--font-mono);
    color: var(--text-strong);
    font-size: 13px;
  }
  .import-bulk-table-notes {
    color: var(--text-muted);
    font-size: 12.5px;
  }

  /* ─── Status badge ─── */
  .import-bulk-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 2px 9px;
    border-radius: 9999px;
    font-size: 12px;
    font-weight: 600;
    letter-spacing: -0.005em;
  }
  .import-bulk-badge-dot {
    width: 6px; height: 6px;
    border-radius: 50%;
    flex-shrink: 0;
  }
  .import-bulk-badge-success {
    color: #3fb950;
    background: rgba(63,185,80,0.13);
    border: 1px solid rgba(63,185,80,0.28);
  }
  .import-bulk-badge-success .import-bulk-badge-dot {
    background: #3fb950;
    box-shadow: 0 0 6px rgba(63,185,80,0.7);
  }
  .import-bulk-badge-warn {
    color: #f0b429;
    background: rgba(240,180,41,0.12);
    border: 1px solid rgba(240,180,41,0.28);
  }
  .import-bulk-badge-warn .import-bulk-badge-dot { background: #f0b429; }
  .import-bulk-badge-info {
    color: #58a6ff;
    background: rgba(88,166,255,0.12);
    border: 1px solid rgba(88,166,255,0.28);
  }
  .import-bulk-badge-info .import-bulk-badge-dot { background: #58a6ff; }
  .import-bulk-badge-error {
    color: #f85149;
    background: rgba(248,81,73,0.12);
    border: 1px solid rgba(248,81,73,0.28);
  }
  .import-bulk-badge-error .import-bulk-badge-dot { background: #f85149; }

  .import-bulk-empty {
    padding: 18px;
    text-align: center;
    color: var(--text-muted);
    font-size: 13.5px;
  }

  .import-bulk-callout {
    margin-top: var(--space-4);
    padding: 12px 14px;
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-left: 3px solid var(--accent);
    border-radius: 10px;
    font-size: 13px;
    color: var(--text-muted);
  }
  .import-bulk-callout em { color: var(--text-strong); font-style: normal; font-weight: 600; }

  .import-bulk-subhead {
    font-family: var(--font-display);
    font-size: 16px;
    font-weight: 700;
    letter-spacing: -0.014em;
    color: var(--text-strong);
    margin: var(--space-5) 0 var(--space-3);
  }
`;

/**
 * Paginate the GitHub "list org repos" endpoint. Caps at MAX_REPOS so a
 * single request can't fan out indefinitely. Throws on non-2xx so the
 * caller can surface a friendly error.
 */
async function fetchOrgRepos(
  org: string,
  token: string
): Promise<GitHubRepo[]> {
  const headers: Record<string, string> = {
    Accept: "application/vnd.github.v3+json",
    "User-Agent": "gluecron/1.0",
    Authorization: `Bearer ${token}`,
  };

  const repos: GitHubRepo[] = [];
  let page = 1;
  while (repos.length < MAX_REPOS) {
    const url = `https://api.github.com/orgs/${encodeURIComponent(
      org
    )}/repos?per_page=${GITHUB_PER_PAGE}&page=${page}&type=all`;
    const res = await fetch(url, { headers });
    if (!res.ok) {
      // Distinguish the three real failure modes the operator can act on
      // instead of dumping a raw GitHub body that hides the actual cause.
      let detail = "";
      try {
        const body = await res.json();
        detail = body?.message ? ` — ${String(body.message)}` : "";
      } catch {
        /* non-JSON body */
      }
      if (res.status === 404) {
        throw new Error(
          `Organization "${org}" not found on GitHub (404)${detail}. Check the spelling.`
        );
      }
      if (res.status === 401) {
        throw new Error(
          `GitHub rejected the token (401)${detail}. The PAT is invalid or expired — mint a new one at github.com/settings/tokens.`
        );
      }
      if (res.status === 403) {
        throw new Error(
          `GitHub forbade the request (403)${detail}. Your token likely lacks the 'read:org' / 'repo' scope, or you've hit the rate limit. Wait an hour or mint a token with the right scopes.`
        );
      }
      throw new Error(`GitHub API error (${res.status})${detail}`);
    }
    let batch: GitHubRepo[];
    try {
      batch = (await res.json()) as GitHubRepo[];
    } catch (err) {
      // A malformed batch shouldn't kill the whole bulk import. Log it
      // (without token leak) and stop pagination — the operator will see
      // whatever we managed to collect so far.
      console.error(
        `[import-bulk] non-JSON response on page ${page} for org ${org}:`,
        err instanceof Error ? err.message : err
      );
      break;
    }
    if (!Array.isArray(batch) || batch.length === 0) break;
    repos.push(...batch);
    if (batch.length < GITHUB_PER_PAGE) break;
    page++;
    if (page > 10) break; // hard page ceiling: 1000 entries, we cap earlier anyway
  }
  return repos.slice(0, MAX_REPOS);
}

function matchesVisibility(repo: GitHubRepo, v: Visibility): boolean {
  if (v === "both") return true;
  if (v === "public") return repo.private === false;
  if (v === "private") return repo.private === true;
  return true;
}

// ─── FORM PAGE ───────────────────────────────────────────────

importBulkRoutes.get("/import/bulk", requireAuth, async (c) => {
  const user = c.get("user")!;
  const error = c.req.query("error");

  return c.html(
    <Layout title="Bulk import from GitHub" user={user}>
      <style dangerouslySetInnerHTML={{ __html: importBulkStyles }} />
      <div class="import-bulk-container">
        {/* ─── Hero ─── */}
        <div class="import-bulk-hero">
          <div class="import-bulk-hero-bg" aria-hidden="true">
            <div class="import-bulk-hero-orb" />
          </div>
          <div class="import-bulk-hero-inner">
            <div class="import-bulk-hero-eyebrow">
              <span class="import-bulk-hero-eyebrow-dot" aria-hidden="true" />
              Bulk migration
            </div>
            <h1 class="import-bulk-hero-title">
              Import{" "}
              <span class="gradient-text">many at once</span>.
            </h1>
            <p class="import-bulk-hero-sub">
              Paste a GitHub org + personal access token. Gluecron clones every
              repo into your namespace as a mirror — sequentially, with per-repo
              status so one failure can't abort the batch.
            </p>
          </div>
        </div>

        {error && (
          <div class="import-bulk-banner import-bulk-banner-error" role="alert">
            <div class="import-bulk-banner-title">Bulk import didn't run</div>
            <div class="import-bulk-banner-detail">
              {decodeURIComponent(error)}
            </div>
          </div>
        )}

        {/* ─── What this does (info panel) ─── */}
        <div class="import-bulk-info">
          <strong>What this does</strong>
          <ul>
            <li>
              Lists every repo in the org via the GitHub API
              (<code>/orgs/{"{org}"}/repos</code>, paginated).
            </li>
            <li>
              Clones each one as a bare mirror into your gluecron account
              (<code>{user.username}/{"{repo}"}</code>).
            </li>
            <li>
              Reports per-repo success / failure / skipped-if-exists at
              the end. One failure does not abort the batch.
            </li>
            <li>
              Hard caps: <code>{MAX_REPOS}</code> repos per run, 500MB per repo.
            </li>
          </ul>
        </div>

        {/* ─── Form section ─── */}
        <div class="import-bulk-section">
          <div class="import-bulk-section-head">
            <div class="import-bulk-section-eyebrow">Configure</div>
            <h2 class="import-bulk-section-title">Org + token</h2>
            <p class="import-bulk-section-desc">
              Token is used only in this request — never stored.
            </p>
          </div>
          <div class="import-bulk-section-body">
            <form method="post" action="/import/bulk">
              <div class="import-bulk-field">
                <label class="import-bulk-field-label">GitHub org</label>
                <input
                  type="text"
                  name="githubOrg"
                  required
                  placeholder="my-company"
                  aria-label="GitHub org"
                  class="import-bulk-input"
                />
              </div>

              <div class="import-bulk-field">
                <label class="import-bulk-field-label">
                  Personal access token <code>repo:read</code> scope
                </label>
                <input
                  type="password"
                  name="githubToken"
                  required
                  placeholder="ghp_xxxxxxxxxxxx"
                  autocomplete="off"
                  aria-label="GitHub personal access token"
                  class="import-bulk-input is-mono"
                />
              </div>

              <div class="import-bulk-field">
                <label class="import-bulk-field-label">Visibility filter</label>
                <select
                  name="visibility"
                  aria-label="Visibility filter"
                  class="import-bulk-select"
                >
                  <option value="both" selected>Both (public + private)</option>
                  <option value="public">Public only</option>
                  <option value="private">Private only</option>
                </select>
              </div>

              <div class="import-bulk-field">
                <label class="import-bulk-toggle">
                  <input type="checkbox" name="dryRun" value="1" checked />
                  <span class="import-bulk-toggle-text">
                    Dry run — preview the list without cloning
                    <span class="import-bulk-toggle-hint">
                      Recommended for the first pass. Uncheck once the preview
                      looks right.
                    </span>
                  </span>
                </label>
              </div>

              <div class="import-bulk-actions">
                <button type="submit" class="btn btn-primary">
                  Run bulk import
                </button>
                <a href="/import" class="btn">
                  Back to /import
                </a>
              </div>
            </form>
          </div>
        </div>
      </div>
    </Layout>
  );
});

// ─── POST HANDLER ────────────────────────────────────────────

importBulkRoutes.post("/import/bulk", requireAuth, async (c) => {
  const user = c.get("user")!;
  const body = await c.req.parseBody();

  const githubOrg = String(body.githubOrg || "").trim();
  const githubToken = String(body.githubToken || "").trim();
  const visibilityRaw = String(body.visibility || "both").trim();
  const visibility: Visibility =
    visibilityRaw === "public" || visibilityRaw === "private"
      ? (visibilityRaw as Visibility)
      : "both";
  const dryRun = Boolean(body.dryRun); // unchecked box = undefined = false

  if (!githubOrg) {
    return c.redirect("/import/bulk?error=GitHub+org+is+required");
  }
  if (!githubToken) {
    return c.redirect(
      "/import/bulk?error=GitHub+token+is+required+%28repo%3Aread+scope%29"
    );
  }

  // Validate the token has at least read access before we start cloning.
  // `GET /user` is the cheapest call that requires a valid token. We also
  // inspect the `X-OAuth-Scopes` header so we can warn early if the token
  // is missing `repo`/`repo:read`.
  try {
    const userRes = await fetch("https://api.github.com/user", {
      headers: {
        Accept: "application/vnd.github.v3+json",
        "User-Agent": "gluecron/1.0",
        Authorization: `Bearer ${githubToken}`,
      },
    });
    if (!userRes.ok) {
      return c.redirect(
        `/import/bulk?error=${encodeURIComponent(
          `Invalid GitHub token (${userRes.status}). Check scope repo:read.`
        )}`
      );
    }
    const scopes = (userRes.headers.get("x-oauth-scopes") || "").toLowerCase();
    if (
      scopes &&
      !scopes.includes("repo") &&
      !scopes.includes("public_repo")
    ) {
      return c.redirect(
        `/import/bulk?error=${encodeURIComponent(
          "Token is missing repo:read scope. Regenerate with repo (or public_repo) checked."
        )}`
      );
    }
  } catch (err) {
    // Network-level failure talking to GitHub. Don't leak err details.
    return c.redirect(
      "/import/bulk?error=Could+not+reach+GitHub+to+validate+the+token"
    );
  }

  // Pull the repo list.
  let allRepos: GitHubRepo[];
  try {
    allRepos = await fetchOrgRepos(githubOrg, githubToken);
  } catch (err) {
    const msg = (err as Error).message || "Unknown error";
    return c.redirect(
      `/import/bulk?error=${encodeURIComponent(msg).slice(0, 400)}`
    );
  }

  if (allRepos.length === 0) {
    return c.redirect(
      `/import/bulk?error=${encodeURIComponent(
        `No repos visible for org "${githubOrg}" with this token.`
      )}`
    );
  }

  // Apply visibility filter + size cap; track why things were skipped.
  const candidates: GitHubRepo[] = [];
  const oversized: { name: string; sizeKB: number }[] = [];
  for (const r of allRepos) {
    if (!matchesVisibility(r, visibility)) continue;
    if (typeof r.size === "number" && r.size > MAX_REPO_SIZE_KB) {
      oversized.push({ name: r.name, sizeKB: r.size });
      continue;
    }
    candidates.push(r);
  }

  // Dry run: render a preview + counts, never touch disk or DB.
  if (dryRun) {
    return c.html(
      <Layout title="Bulk import preview" user={user}>
        <style dangerouslySetInnerHTML={{ __html: importBulkStyles }} />
        <div class="import-bulk-container">
          <div class="import-bulk-hero">
            <div class="import-bulk-hero-bg" aria-hidden="true">
              <div class="import-bulk-hero-orb" />
            </div>
            <div class="import-bulk-hero-inner">
              <div class="import-bulk-hero-eyebrow">
                <span class="import-bulk-hero-eyebrow-dot" aria-hidden="true" />
                Preview only — nothing imported yet
              </div>
              <h1 class="import-bulk-hero-title">
                Bulk import{" "}
                <span class="gradient-text">dry run</span>.
              </h1>
              <p class="import-bulk-hero-sub">
                This is what gluecron would clone from{" "}
                <code>{githubOrg}</code> when you uncheck the dry-run box.
              </p>
            </div>
          </div>

          <div class="import-bulk-summary">
            <span>
              Org <code>{githubOrg}</code>
            </span>
            <span>
              Visibility <code>{visibility}</code>
            </span>
            <span class="import-bulk-summary-stat">
              <span class="num">{candidates.length}</span> to import
            </span>
            {oversized.length > 0 && (
              <span class="import-bulk-summary-stat">
                <span class="num">{oversized.length}</span> skipped (&gt;500MB)
              </span>
            )}
          </div>

          <ResultsTable
            rows={candidates.map((r) => ({
              name: sanitizeRepoName(r.name),
              status: "dry-run",
              notes: `${r.private ? "private" : "public"} · ${(
                r.size / 1024
              ).toFixed(1)} MB`,
            }))}
          />

          {oversized.length > 0 && (
            <>
              <h3 class="import-bulk-subhead">Skipped — over 500MB</h3>
              <ResultsTable
                rows={oversized.map((r) => ({
                  name: sanitizeRepoName(r.name),
                  status: "too-large",
                  notes: `${(r.sizeKB / 1024).toFixed(1)} MB`,
                }))}
              />
            </>
          )}

          <div class="import-bulk-callout">
            Looks good? Go back and uncheck <em>Dry run</em> to actually import.
          </div>

          <div class="import-bulk-actions">
            <a href="/import/bulk" class="btn btn-primary">
              Back to form
            </a>
          </div>
        </div>
      </Layout>
    );
  }

  // Real run: clone each candidate sequentially. Collect results.
  const results: ImportOneRepoResult[] = [];
  for (const r of candidates) {
    // eslint-disable-next-line no-await-in-loop
    const res = await importOneRepo({
      cloneUrl: r.clone_url,
      targetName: r.name,
      ownerId: user.id,
      ownerUsername: user.username,
      token: githubToken,
      description: r.description,
      isPrivate: r.private,
      defaultBranch: r.default_branch,
    });
    results.push(res);
  }

  for (const o of oversized) {
    results.push({
      status: "failed",
      name: sanitizeRepoName(o.name),
      notes: `Skipped — over 500MB (${(o.sizeKB / 1024).toFixed(1)} MB)`,
    });
  }

  const counts = results.reduce(
    (acc, r) => {
      acc[r.status] = (acc[r.status] || 0) + 1;
      return acc;
    },
    {} as Record<string, number>
  );

  return c.html(
    <Layout title="Bulk import results" user={user}>
      <style dangerouslySetInnerHTML={{ __html: importBulkStyles }} />
      <div class="import-bulk-container">
        <div class="import-bulk-hero">
          <div class="import-bulk-hero-bg" aria-hidden="true">
            <div class="import-bulk-hero-orb" />
          </div>
          <div class="import-bulk-hero-inner">
            <div class="import-bulk-hero-eyebrow">
              <span class="import-bulk-hero-eyebrow-dot" aria-hidden="true" />
              Bulk migration complete
            </div>
            <h1 class="import-bulk-hero-title">
              Bulk import{" "}
              <span class="gradient-text">results</span>.
            </h1>
            <p class="import-bulk-hero-sub">
              From <code>{githubOrg}</code> into{" "}
              <code>{user.username}</code>.
            </p>
          </div>
        </div>

        <div class="import-bulk-summary">
          <span class="import-bulk-summary-stat">
            <span class="num">{counts["success"] || 0}</span> imported
          </span>
          <span class="import-bulk-summary-stat">
            <span class="num">{counts["skipped-exists"] || 0}</span> skipped
          </span>
          <span class="import-bulk-summary-stat">
            <span class="num">{counts["failed"] || 0}</span> failed
          </span>
        </div>

        <ResultsTable rows={results} />

        <div class="import-bulk-actions">
          <a href={`/${user.username}`} class="btn btn-primary">
            View my repositories
          </a>
          <a href="/import/bulk" class="btn">
            Run another import
          </a>
        </div>
      </div>
    </Layout>
  );
});

// ─── COMPONENTS ──────────────────────────────────────────────

function ResultsTable({
  rows,
}: {
  rows: { name: string; status: string; notes: string }[];
}) {
  if (rows.length === 0) {
    return (
      <div class="import-bulk-table-wrap">
        <div class="import-bulk-empty">No rows.</div>
      </div>
    );
  }
  return (
    <div class="import-bulk-table-wrap">
      <table class="import-bulk-table">
        <thead>
          <tr>
            <th>Name</th>
            <th>Status</th>
            <th>Notes</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr>
              <td class="import-bulk-table-name">{r.name}</td>
              <td>
                <StatusBadge status={r.status} />
              </td>
              <td class="import-bulk-table-notes">{r.notes}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function StatusBadge({ status }: { status: string }) {
  const cls =
    status === "success"
      ? "import-bulk-badge-success"
      : status === "skipped-exists"
        ? "import-bulk-badge-warn"
        : status === "dry-run"
          ? "import-bulk-badge-info"
          : status === "too-large"
            ? "import-bulk-badge-warn"
            : "import-bulk-badge-error";
  return (
    <span class={`import-bulk-badge ${cls}`}>
      <span class="import-bulk-badge-dot" aria-hidden="true" />
      {status}
    </span>
  );
}

export default importBulkRoutes;