File size: 30,111 Bytes
2344c18
5fe0dfe
8e81806
 
faa6841
8e81806
 
5fe0dfe
8e81806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60bb2e1
 
8e81806
 
 
 
 
 
 
60bb2e1
 
8e81806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33d9794
 
 
 
8e81806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33d9794
 
 
 
8e81806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3083c54
 
 
 
faa6841
 
 
 
33d9794
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3083c54
8e81806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dbbd88
8e81806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60bb2e1
8e81806
 
 
 
 
 
 
 
 
 
 
 
33d9794
eef8189
 
60bb2e1
 
8e81806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60bb2e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e81806
 
60bb2e1
8e81806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33d9794
2ba2111
 
 
 
 
 
 
 
 
 
 
 
 
8e81806
60bb2e1
 
 
 
 
 
8e81806
 
 
 
 
 
7881608
 
 
 
 
 
6dbbd88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e81806
 
5e16b80
 
faa6841
579f8aa
 
 
 
5e16b80
 
 
 
 
 
579f8aa
 
 
faa6841
5e16b80
 
 
 
 
 
 
faa6841
 
8e81806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed684ff
8e81806
 
 
 
ed684ff
8e81806
 
 
 
 
 
 
 
 
 
 
 
 
2344c18
ed684ff
33d9794
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
const express = require('express');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const premiumStore = require('./premiumStore');

console.log(">>> [MODULE] server.js: Initializing...");
const app = express();
const port = process.env.PORT || 7860;


// Discord OAuth2 Config — reads from multiple possible env var names
const CLIENT_SECRET = process.env.CLIENT_SECRET || process.env.DISCORD_CLIENT_SECRET || '';
const REDIRECT_URI = process.env.REDIRECT_URI || process.env.DISCORD_REDIRECT_URL || '';

// Store reference to the Discord client (set from index.js)
let discordClient = null;
let commandsDataRef = null;

// Session store (persisted to disk so logins survive restarts)
const storage = require('./storage');
const SESSION_FILE = path.join(storage.PERSISTENT_DIR, 'sessions.json');
let sessions = new Map();

// Load sessions from disk on startup
try {
    if (fs.existsSync(SESSION_FILE)) {
        const content = fs.readFileSync(SESSION_FILE, 'utf8').trim();
        if (content) {
            const raw = JSON.parse(content);
            if (raw && typeof raw === 'object') {
                sessions = new Map(Object.entries(raw));
                console.log(`[*] Dashboard: Loaded ${sessions.size} persistent session(s).`);
            }
        }
    }
} catch (e) {
    console.error(`[*] Dashboard: Failed to load sessions: ${e.message}`);
}
console.log("[*] Dashboard: Session system initialized.");

function saveSessions() {
    try {
        const dir = path.dirname(SESSION_FILE);
        if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
        const obj = Object.fromEntries(sessions);
        fs.writeFileSync(SESSION_FILE, JSON.stringify(obj), 'utf8');
    } catch (e) {}
}

// In-memory log buffer
const logBuffer = [];
const MAX_LOGS = 200;

let isHijacked = false;
function hijackConsole() {
    if (isHijacked) return;
    const origLog = console.log;
    const origErr = console.error;
    console.log = (...args) => {
        const line = args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
        logBuffer.push(line);
        if (logBuffer.length > MAX_LOGS) logBuffer.shift();
        origLog.apply(console, args);
    };
    console.error = (...args) => {
        const line = '[Error] ' + args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
        logBuffer.push(line);
        if (logBuffer.length > MAX_LOGS) logBuffer.shift();
        origErr.apply(console, args);
    };
    isHijacked = true;
}

app.use(express.json());

function hasDashboardPermissions(permissionBits) {
    try {
        const perms = BigInt(permissionBits || '0');
        return (perms & BigInt(0x20)) !== BigInt(0) || (perms & BigInt(0x8)) !== BigInt(0);
    } catch (e) {
        return false;
    }
}

// --- Helper: Get redirect URI ---
function getRedirectUri(req) {
    // Prioritize building the URI dynamically from the incoming request.
    // This allows duplicated/cloned Spaces to work perfectly out-of-the-box.
    if (req) {
        const host = req.get('host');
        const protocol = req.protocol === 'http' && host.includes('.hf.space') ? 'https' : req.protocol;
        const path = req.path === '/' ? '/' : '/callback';
        return `${protocol}://${host}${path}`;
    }

    if (REDIRECT_URI) return REDIRECT_URI;

    const spaceId = process.env.SPACE_ID;
    if (spaceId) {
        const host = spaceId.includes('/') ? spaceId.replace('/', '-').toLowerCase() : spaceId.toLowerCase();
        return `https://${host}.hf.space/callback`;
    }
    return `http://localhost:${port}/callback`;
}

// --- Helper: Get Client ID from bot ---
function getClientId() {
    return discordClient?.user?.id || process.env.CLIENT_ID || process.env.DISCORD_CLIENT_ID || '';
}

// --- Helper: Parse session cookie ---
function getSession(req) {
    const cookies = (req.headers.cookie || '').split(';').reduce((acc, c) => {
        const [k, v] = c.trim().split('=');
        if (k && v) acc[k] = v;
        return acc;
    }, {});
    const sid = cookies['fb_session'];
    if (sid && sessions.has(sid)) return sessions.get(sid);
    return null;
}

// --- Auth Middleware ---
function requireAuth(req, res, next) {
    const session = getSession(req);
    if (session && session.user) {
        req.user = session.user; // Attach user for convenience
        return next();
    }
    res.status(401).json({ error: 'Unauthorized' });
}

// --- Attach user to req ---
app.use((req, res, next) => {
    req.dashSession = getSession(req);
    next();
});

// --- Static Assets ---
app.get('/', (req, res) => {
    // If we get an OAuth code on the root route, handle it using the root as the redirect_uri
    if (req.query.code) {
        console.log("[Dashboard] Received OAuth code on root route, handling...");
        return handleOAuthCallback(req, res, getRedirectUri(req));
    }
    res.sendFile(path.join(__dirname, 'dashboard.html'));
});

app.get('/dashboard', (req, res) => {
    res.sendFile(path.join(__dirname, 'dashboard.html'));
});
app.get('/logo.png', (req, res) => {
    const logo = path.join(__dirname, 'logo.png');
    if (fs.existsSync(logo)) res.sendFile(logo);
    else res.status(404).send('Not found');
});

// Returns 200 as long as the web server is running.
// This prevents Hugging Face and other platforms from restarting the space 
// while the Discord bot is still performing its initial connection handshake.
app.get('/healthz', (req, res) => {
    const discordReady = !!(discordClient && discordClient.isReady && discordClient.isReady());
    return res.status(200).json({
        ok: true,
        webReady: true,
        discordReady: discordReady,
        guilds: discordReady ? (discordClient.guilds?.cache?.size || 0) : 0
    });
});

app.get('/tos', (req, res) => {
    res.sendFile(path.join(__dirname, 'tos.html'));
});

app.get('/privacy', (req, res) => {
    res.sendFile(path.join(__dirname, 'privacy.html'));
});

app.get('/league', (req, res) => {
    res.sendFile(path.join(__dirname, 'league.html'));
});

app.get('/premium', (req, res) => {
    res.sendFile(path.join(__dirname, 'premium.html'));
});

app.get('/aliases', (req, res) => {
    res.sendFile(path.join(__dirname, 'aliases.html'));
});

app.get('/stats', (req, res) => {
    res.sendFile(path.join(__dirname, 'stats.html'));
});

app.get('/scheduling', (req, res) => {
    res.sendFile(path.join(__dirname, 'scheduling.html'));
});

app.get('/profiles', (req, res) => {
    res.sendFile(path.join(__dirname, 'profiles.html'));
});


// --- Discord OAuth2: Step 1 — Redirect to Discord ---
app.get('/auth/login', (req, res) => {
    const clientId = getClientId();
    const redirect = encodeURIComponent(getRedirectUri(req));
    console.log(`[Dashboard] Starting OAuth login. Redirect URI: ${getRedirectUri(req)}`);
    const url = `https://discord.com/api/oauth2/authorize?client_id=${clientId}&redirect_uri=${redirect}&response_type=code&scope=identify%20guilds`;
    res.redirect(url);
});

async function fetchWithRetry(url, options, retries = 3) {
    const endpoints = [
        'https://discord.com',
        'https://canary.discord.com',
        'https://ptb.discord.com'
    ];

    for (let i = 0; i < endpoints.length; i++) {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 20000); // 20s timeout
        
        try {
            let targetUrl = url;
            const currentBase = endpoints[i];
            
            // Only swap if it's a discord API call
            if (url.includes('discord.com/api')) {
                targetUrl = url.replace('https://discord.com', currentBase);
                console.log(`[Dashboard] Connection Attempt ${i + 1} via ${new URL(currentBase).hostname}...`);
            }
            
            const res = await fetch(targetUrl, { 
                ...options, 
                signal: controller.signal 
            });
            clearTimeout(timeoutId);

            if (!res.ok) {
                const text = await res.text().catch(() => '');
                console.warn(`[Dashboard] API returned ${res.status} from ${new URL(currentBase).hostname}`);
                if (i === endpoints.length - 1) throw new Error(`HTTP ${res.status}: ${text}`);
                continue; // Try next endpoint
            }
            return res;
        } catch (err) {
            clearTimeout(timeoutId);
            const isTimeout = err.name === 'AbortError';
            console.warn(`[Dashboard] Attempt ${i + 1} (${new URL(endpoints[i]).hostname}) failed: ${isTimeout ? 'Timeout' : err.message}`);
            
            if (i === endpoints.length - 1) throw err;
            
            // Short delay before next endpoint
            await new Promise(r => setTimeout(r, 1000));
        }
    }
}

// --- Discord OAuth2: Step 2 — Callback from Discord ---
// Support both /callback and /auth/callback to match any Discord redirect config
async function handleOAuthCallback(req, res, overrideRedirectUri) {
    const { code, error, error_description } = req.query;
    
    if (error) {
        console.error(`[Dashboard] Discord returned error: ${error} (${error_description})`);
        return res.redirect(`/?error=${error}`);
    }

    if (!code) {
        console.warn(`[Dashboard] No code found in query parameters. URL: ${req.originalUrl}`);
        return res.redirect('/?error=no_code');
    }
    
    // Ensure overrideRedirectUri is a string and not the 'next' function from Express
    const usedRedirectUri = (typeof overrideRedirectUri === 'string') ? overrideRedirectUri : getRedirectUri(req);
    console.log(`[Dashboard] Handling OAuth callback. Code: ${code.substring(0, 5)}... Redirect URI: ${usedRedirectUri}`);

    if (!CLIENT_SECRET) {
        console.error('[Dashboard] CRITICAL: CLIENT_SECRET is missing from environment variables.');
        return res.redirect('/?error=server_error');
    }

    try {
        console.log(`[Dashboard] Exchanging code for token... (Redirect URI: ${getRedirectUri()})`);
        // Exchange code for token
        const tokenRes = await fetchWithRetry('https://discord.com/api/oauth2/token', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                client_id: getClientId(),
                client_secret: CLIENT_SECRET,
                grant_type: 'authorization_code',
                code,
                redirect_uri: usedRedirectUri
            })
        });
        
        const tokenData = await tokenRes.json();
        if (!tokenData.access_token) {
            console.error('[Dashboard] Token exchange failed:', tokenData);
            return res.redirect('/?error=token_failed');
        }

        console.log(`[Dashboard] Token received. Fetching user profile...`);
        // Fetch user profile
        const userRes = await fetchWithRetry('https://discord.com/api/users/@me', {
            headers: { Authorization: `Bearer ${tokenData.access_token}` }
        });
        const user = await userRes.json();
        if (!user.id) {
            console.error('[Dashboard] Failed to fetch user profile:', user);
            return res.redirect('/?error=user_failed');
        }

        // Fetch user guilds
        console.log(`[Dashboard] Fetching guilds for user ${user.username} (${user.id})...`);
        const guildsRes = await fetchWithRetry('https://discord.com/api/users/@me/guilds', {
            headers: { Authorization: `Bearer ${tokenData.access_token}` }
        });
        const userGuilds = await guildsRes.json();
        
        if (!Array.isArray(userGuilds)) {
            console.error('[Dashboard] Failed to fetch guilds:', userGuilds);
        } else {
            console.log(`[Dashboard] Found ${userGuilds.length} guilds for user.`);
        }

        // Create session
        const sid = crypto.randomBytes(32).toString('hex');
        sessions.set(sid, {
            user: {
                id: user.id,
                username: user.username,
                avatar: user.avatar
                    ? `https://cdn.discord.com/avatars/${user.id}/${user.avatar}.png`
                    : `https://cdn.discord.com/embed/avatars/${parseInt(user.discriminator || '0') % 5}.png`
            },
            guilds: Array.isArray(userGuilds) ? userGuilds : [],
            createdAt: Date.now()
        });
        saveSessions();

        // Set cookie (7 days)
        res.cookie('fb_session', sid, {
            httpOnly: true,
            maxAge: 7 * 24 * 60 * 60 * 1000,
            sameSite: 'lax'
        });

        res.redirect('/?login=success');
    } catch (err) {
        console.error('[Dashboard] OAuth error:', err);
        res.redirect('/?error=server_error');
    }
}
app.get('/callback', handleOAuthCallback);
app.get('/auth/callback', handleOAuthCallback);

// --- Check Auth Status ---
app.get('/api/me', (req, res) => {
    const session = getSession(req);
    if (session && session.user) {
        res.json({ loggedIn: true, user: session.user });
    } else {
        res.json({ loggedIn: false });
    }
});

// --- Logout ---
app.get('/auth/logout', (req, res) => {
    const cookies = (req.headers.cookie || '').split(';').reduce((acc, c) => {
        const [k, v] = c.trim().split('=');
        if (k && v) acc[k] = v;
        return acc;
    }, {});
    const sid = cookies['fb_session'];
    if (sid) {
        sessions.delete(sid);
        saveSessions();
    }
    res.clearCookie('fb_session');
    res.redirect('/');
});

// --- Stats ---
app.get('/api/stats', requireAuth, (req, res) => {
    if (!discordClient || !discordClient.isReady()) {
        return res.json({ servers: 0, members: 0, uptime: '—', commands: 0 });
    }
    const up = process.uptime();
    const d = Math.floor(up / 86400);
    const h = Math.floor(up / 3600) % 24;
    const m = Math.floor(up / 60) % 60;
    const upStr = d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`;

    const totalMembers = discordClient.guilds.cache.reduce((acc, g) => acc + g.memberCount, 0);
    const botId = discordClient.user?.id;
    const inviteUrl = botId
        ? `https://discord.com/api/oauth2/authorize?client_id=${botId}&permissions=8&scope=bot%20applications.commands`
        : '#';

    res.json({
        servers: discordClient.guilds.cache.size,
        members: totalMembers,
        uptime: upStr,
        commands: 28, // Matches the full command registry count
        inviteUrl
    });
});

// --- Server List ---
// --- Server List (shared with bot + permissions) ---
let cachedOwnerId = null;
app.get('/api/servers', requireAuth, async (req, res) => {
    try {
        if (!discordClient || !discordClient.isReady()) {
            return res.json({ pending: true, servers: [] });
        }

        const userGuilds = req.dashSession.guilds || [];
        
        // recognize owner (cached to avoid redundant API calls)
        if (!cachedOwnerId) {
            const app = await discordClient.application.fetch().catch(() => null);
            if (app) {
                cachedOwnerId = app.owner?.ownerId || app.owner?.id;
                // Support teams
                if (!cachedOwnerId && app.owner?.members) {
                    // Just check the first member as a fallback if ownerId is missing
                    const firstMember = Array.from(app.owner.members.values())[0];
                    cachedOwnerId = firstMember?.user?.id || firstMember?.id;
                }
            }
        }
        
        const isBotOwner = req.dashSession.user.id === cachedOwnerId;
        console.log(`[Dashboard] Request by ${req.dashSession.user.username} (Owner: ${isBotOwner})`);

        // Filter guilds to only those that the user is actually in AND has permissions for.
        const mutualGuilds = userGuilds
            .filter(ug => discordClient.guilds.cache.has(ug.id))
            .filter(Boolean);
        
        const manageableGuilds = mutualGuilds.filter(ug => {
            const permBits = ug.permissions ?? ug.permissions_new;
            return hasDashboardPermissions(permBits);
        });
        
        const guildsToShow = manageableGuilds;
        
        const visibleGuilds = guildsToShow
            .map(ug => discordClient.guilds.cache.get(ug.id))
            .filter(Boolean);

        const list = visibleGuilds.map(g => ({
            name: g.name,
            id: g.id,
            members: g.memberCount || 0,
            icon: g.iconURL({ size: 64 }) || null
        }));

        if (isBotOwner) console.log(`[Dashboard] Owner access verified for ${req.dashSession.user.username}`);
        console.log(`[Dashboard] Serving ${list.length} managed servers to ${req.dashSession.user.username}`);
        res.json({ pending: false, servers: list });
    } catch (err) {
        console.error('[Dashboard] /api/servers failed:', err);
        res.status(500).json({ pending: false, servers: [], error: 'Failed to load servers' });
    }
});

// --- Guild Config (Prefix) ---
app.get('/api/config/:guildId', requireAuth, (req, res) => {
    const { guildId } = req.params;
    const userGuilds = req.dashSession.guilds || [];
    const ug = userGuilds.find(g => g.id === guildId);
    
    if (!ug) return res.status(403).json({ error: 'Access denied' });
    const hasPerms = (BigInt(ug.permissions) & BigInt(0x20)) || (BigInt(ug.permissions) & BigInt(0x8));
    if (!hasPerms) return res.status(403).json({ error: 'Missing permissions' });

    const storage = require('./storage');
    const roleStorage = require('./roleStorage');
    const config = storage.data.config[guildId] || {};
    res.json({ 
        prefix: storage.getPrefix(guildId),
        autoFriendlyEnabled: config.autoFriendlyEnabled || false,
        autoFriendlyInterval: config.autoFriendlyInterval || 40,
        autoFriendlyChannel: config.autoFriendlyChannel || null,
        postEnabled: !!config.postEnabled, // Default to false (off)
        postChannelId: config.postChannelId || null,
        friendlyText: config.friendlyText || "⭐▬▬▬▬▬ **FRIENDLY** ▬▬▬▬▬⭐\n🤝 Session\n🟩 I'm In\n🟥 Busy\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n🗳️ Needed: {needed}\n@everyone",
        cleanupHours: config.cleanupHours || 2,
        lineupCleanupHours: config.lineupCleanupHours || 2,
        remindersEnabled: !!config.remindersEnabled,
        remindersLead: config.remindersLead || 30,
        aliases: config.aliases || {},
        leaderboardChannel: config.leaderboardChannel || null,
        statsFrequency: config.statsFrequency || 'never',
        whitelistedRoles: roleStorage.roles[guildId] || []
    });
});

app.get('/api/channels/:guildId', requireAuth, (req, res) => {
    const { guildId } = req.params;
    if (!discordClient) return res.json([]);
    const guild = discordClient.guilds.cache.get(guildId);
    if (!guild) return res.json([]);

    const channels = guild.channels.cache
        .filter(c => c.isTextBased())
        .map(c => ({ id: c.id, name: c.name }));
    res.json(channels);
});

app.get('/api/roles/:guildId', requireAuth, (req, res) => {
    const { guildId } = req.params;
    const userGuilds = req.dashSession.guilds || [];
    const ug = userGuilds.find(g => g.id === guildId);
    
    if (!ug) return res.status(403).json({ error: 'Access denied' });
    const hasPerms = (BigInt(ug.permissions) & BigInt(0x20)) || (BigInt(ug.permissions) & BigInt(0x8));
    if (!hasPerms) return res.status(403).json({ error: 'Missing permissions' });

    if (!discordClient || !discordClient.isReady()) return res.json([]);
    const guild = discordClient.guilds.cache.get(guildId);
    if (!guild) return res.json([]);

    const roles = guild.roles.cache
        .filter(r => r.name !== '@everyone')
        .map(r => ({ id: r.id, name: r.name, color: r.hexColor }));
    res.json(roles);
});

app.post('/api/config/:guildId', requireAuth, (req, res) => {
    const { guildId } = req.params;
    const { prefix, autoFriendlyEnabled, autoFriendlyInterval, autoFriendlyChannel, postEnabled, postChannelId, friendlyText, cleanupHours, lineupCleanupHours, remindersEnabled, remindersLead, aliases, leaderboardChannel, statsFrequency, whitelistedRoles } = req.body;
    const userGuilds = req.dashSession.guilds || [];
    const ug = userGuilds.find(g => g.id === guildId);

    if (!ug) return res.status(403).json({ error: 'Access denied' });
    const hasPerms = (BigInt(ug.permissions) & BigInt(0x20)) || (BigInt(ug.permissions) & BigInt(0x8));
    if (!hasPerms) return res.status(403).json({ error: 'Missing permissions' });

    const storage = require('./storage');
    
    if (prefix) {
        if (prefix.length > 5) return res.status(400).json({ error: 'Invalid prefix' });
        storage.setPrefix(guildId, prefix);
    }

    if (storage.data.config[guildId] === undefined) storage.data.config[guildId] = {};
    
    if (autoFriendlyEnabled !== undefined) storage.data.config[guildId].autoFriendlyEnabled = !!autoFriendlyEnabled;
    if (autoFriendlyInterval !== undefined) storage.data.config[guildId].autoFriendlyInterval = parseInt(autoFriendlyInterval) || 40;
    if (autoFriendlyChannel !== undefined) storage.data.config[guildId].autoFriendlyChannel = autoFriendlyChannel;
    if (postEnabled !== undefined) storage.data.config[guildId].postEnabled = !!postEnabled;
    if (postChannelId !== undefined) storage.data.config[guildId].postChannelId = postChannelId;
    if (friendlyText !== undefined) storage.data.config[guildId].friendlyText = friendlyText;
    if (cleanupHours !== undefined) storage.data.config[guildId].cleanupHours = parseInt(cleanupHours) || 2;
    if (lineupCleanupHours !== undefined) storage.data.config[guildId].lineupCleanupHours = parseInt(lineupCleanupHours) || 2;
    if (remindersEnabled !== undefined) storage.data.config[guildId].remindersEnabled = !!remindersEnabled;
    if (remindersLead !== undefined) storage.data.config[guildId].remindersLead = parseInt(remindersLead) || 30;
    if (aliases !== undefined) storage.data.config[guildId].aliases = aliases;
    if (leaderboardChannel !== undefined) {
        if (storage.data.config[guildId].leaderboardChannel !== leaderboardChannel) {
            storage.data.config[guildId].lastLeaderboard = 0;
            storage.data.config[guildId].leaderboardMessageId = null;
        }
        storage.data.config[guildId].leaderboardChannel = leaderboardChannel;
    }
    if (statsFrequency !== undefined) {
        if (storage.data.config[guildId].statsFrequency !== statsFrequency) {
            storage.data.config[guildId].lastLeaderboard = 0;
        }
        storage.data.config[guildId].statsFrequency = statsFrequency;
    }

    if (whitelistedRoles !== undefined) {
        const roleStorage = require('./roleStorage');
        roleStorage.roles[guildId] = Array.isArray(whitelistedRoles) ? whitelistedRoles : [];
        roleStorage.save();
    }

    storage.save('config');
    res.json({ success: true, message: 'Settings updated successfully' });
});

// --- Command List ---
app.get('/api/commands', requireAuth, (req, res) => {
const fullCommands = [
  { name: 'friendly', description: 'Start a match poll for players to join', staff: true },
  { name: 'lineup', description: 'Generate the interactive lineup board', staff: true },
  { name: 'scrimlineup', description: 'Generate a scrimmage lineup board with two teams facing each other', staff: true },
  { name: 'lineupimage', description: 'Generate a high-quality visual lineup image', staff: true },
  { name: 'leaguematch', description: 'Schedule a league match with an opponent', staff: true },
        { name: 'win', description: 'Record a match victory', staff: true },
        { name: 'loss', description: 'Record a match defeat', staff: true },
        { name: 'draw', description: 'Record a match draw', staff: true },
        { name: 'managerlineup', description: 'Open the advanced GUI lineup editor', staff: true },
        { name: 'tactic', description: 'Show tactical analysis for a formation', staff: true },
        { name: 'teamrandom', description: 'Randomize players into balanced teams', staff: true },
        { name: 'swap', description: 'Swap two players on the lineup board', staff: true },
        { name: 'sendlink', description: 'Send a quick match or lobby link', staff: true },
        
        { name: 'setup', description: 'Open the bot settings configuration panel', admin: true },
        { name: 'clear', description: 'Bulk delete messages from the channel', admin: true },
        { name: 'lock', description: 'Lock the channel to prevent messaging', admin: true },
        { name: 'unlock', description: 'Unlock the channel for messaging', admin: true },
        { name: 'addrole', description: 'Add a role to the bot staff whitelist', admin: true },
        { name: 'removerole', description: 'Remove a role from the whitelist', admin: true },
        { name: 'sync', description: 'Synchronize all slash commands', admin: true },

        { name: 'ping', description: 'Check the bot response latency' },
        { name: 'help', description: 'View the full list of available commands' },
        { name: 'record', description: 'View the server global match record' },
        { name: 'profile', description: 'View your player profile stats' },
        { name: 'profileimage', description: 'Generate a visual player profile card' },
        { name: 'playerstats', description: 'View detailed stats for a player' },
        { name: 'top', description: 'Show the leaderboard of top players' },
        { name: 'matchpredict', description: 'Get an AI prediction for the current lineup' },
        { name: 'friendlybotsettings', description: 'View bot status and permissions' }
    ];

    res.json(fullCommands);
});

// --- Premium API (public) ---
app.get('/api/premium/list', async (req, res) => {
    const allPremium = premiumStore.getAllPremiumUsers();
    const list = await Promise.all(Object.entries(allPremium).map(async ([userId, record]) => {
        let userTag = userId;
        let avatarUrl = '';
        try {
            if (discordClient) {
                const user = await discordClient.users.fetch(userId).catch(() => null);
                if (user) {
                    userTag = user.tag;
                    avatarUrl = user.displayAvatarURL({ size: 32, dynamic: true });
                }
            }
        } catch (e) {}
        return { userId, userTag, avatarUrl, grantedAt: record.grantedAt, reason: record.reason };
    }));
    res.json({ list });
});

// --- Premium API (auth only) ---
app.get('/api/premium', requireAuth, (req, res) => {
    const userPremium = premiumStore.isPremium(req.user.id);
    res.json({ premium: userPremium });
});

// --- Invite URL ---
app.get('/api/invite', (req, res) => {
    if (!discordClient || !discordClient.user) return res.redirect('/');
    const url = `https://discord.com/api/oauth2/authorize?client_id=${discordClient.user.id}&permissions=8&scope=bot%20applications.commands`;
    res.redirect(url);
});

// --- Logs ---
app.get('/api/logs', requireAuth, (req, res) => {
    res.json({ logs: logBuffer.slice(-100) });
});

// --- Actions ---
app.post('/api/action/:name', requireAuth, async (req, res) => {
    const action = req.params.name;

    if (action === 'sync' && discordClient && commandsDataRef) {
        let count = 0;
        for (const guild of discordClient.guilds.cache.values()) {
            await guild.commands.set(commandsDataRef).catch(() => {});
            count++;
        }
        return res.json({ message: `✅ Synced commands to ${count} servers!` });
    }

    if (action === 'backup') {
        return res.json({ message: '☁️ Cloud backup triggered! Check Discord for confirmation.' });
    }

    if (action === 'restart') {
        res.json({ message: '🔁 Restarting bot in 2 seconds...' });
        setTimeout(() => process.exit(1), 2000);
        return;
    }

    res.json({ message: 'Unknown action.' });
});

// --- Start ---
function startServer(client, cmdsData) {
    console.log("[*] Dashboard: startServer() called. Initializing express...");
    const net = require('net');
    const checkServer = net.createServer();

    checkServer.on('listening', () => {
        checkServer.close(() => {
            console.log(`[*] Port ${port} is available, starting server...`);
            startServerInternal(client, cmdsData);
        });
    });

    checkServer.on('error', (err) => {
        if (err.code === 'EADDRINUSE') {
            console.error(`[!] ERROR: Port ${port} is already in use. Another bot instance is running.`);
            console.error(`[!] Please close other instances before starting this one.`);
            process.exit(1);
        } else {
            console.error(`[!] Server error: ${err.message}`);
            process.exit(1);
        }
    });

    checkServer.listen(port, '0.0.0.0');
}

function startServerInternal(client, cmdsData) {
    hijackConsole();
    discordClient = client || null;
    commandsDataRef = cmdsData || null;

    app.listen(port, '0.0.0.0', () => {
        const finalRedirect = getRedirectUri();
        console.log(`[*] --------------------------------------------------`);
        console.log(`[*] Web Server running on port ${port}`);
        console.log(`[*] --------------------------------------------------`);
        console.log(`[*] DASHBOARD URL: ${finalRedirect.replace('/callback', '').replace('/auth/callback', '')}`);
        console.log(`[*] REDIRECT URI:  ${finalRedirect}`);
        console.log(`[*] --------------------------------------------------`);
        console.log(`[*] IMPORTANT: Ensure the REDIRECT URI above is added exactly to your`);
        console.log(`[*] Discord Developer Portal -> OAuth2 -> Redirects section.`);
        console.log(`[*] --------------------------------------------------`);
    });
}


module.exports = { startServer, app };