File size: 27,432 Bytes
63870b6
 
 
adab8e7
63870b6
 
 
570e8f9
63870b6
 
 
02d31eb
 
 
63870b6
 
 
02d31eb
f899730
ac3ce05
02d31eb
63870b6
 
 
02d31eb
adab8e7
63870b6
 
02d31eb
63870b6
02d31eb
 
 
63870b6
02d31eb
63870b6
 
 
 
 
e17ec72
63870b6
 
 
b906a7a
985ea6c
 
b906a7a
 
 
 
 
 
 
985ea6c
 
b906a7a
 
 
f899730
 
 
 
 
 
 
e17ec72
63870b6
 
 
f899730
 
 
 
 
 
 
 
8086716
 
f899730
 
 
8086716
f899730
adab8e7
f899730
 
 
8086716
 
f899730
 
 
ec05ee9
 
 
bae29e3
ec05ee9
 
 
8086716
 
 
 
f899730
 
 
 
8086716
f899730
adab8e7
8086716
 
f899730
8086716
adab8e7
 
8086716
f899730
8086716
f899730
8086716
 
 
 
 
63870b6
8086716
 
63870b6
8086716
adab8e7
 
 
8086716
 
63870b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb85bb8
63870b6
 
adab8e7
63870b6
 
 
 
 
 
 
 
adab8e7
83b38ba
63870b6
 
 
f899730
 
8086716
63870b6
adab8e7
63870b6
 
adab8e7
 
f899730
 
8086716
63870b6
 
 
adab8e7
63870b6
 
 
adab8e7
63870b6
 
f899730
8086716
 
63870b6
 
 
 
 
 
f899730
8086716
 
f899730
 
570e8f9
adab8e7
8086716
63870b6
 
 
f899730
adab8e7
f899730
8086716
adab8e7
63870b6
 
 
adab8e7
63870b6
adab8e7
8086716
f899730
adab8e7
 
 
f899730
3617142
f899730
adab8e7
63870b6
 
adab8e7
02d31eb
 
 
 
 
 
 
adab8e7
02d31eb
 
 
 
 
 
 
dd3f8ec
8d1eff1
dd3f8ec
f899730
adab8e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63870b6
8d1eff1
adab8e7
 
 
 
 
 
02d31eb
 
adab8e7
dd3f8ec
 
 
 
adab8e7
dd3f8ec
 
adab8e7
dd3f8ec
 
 
adab8e7
dd3f8ec
63870b6
 
dd3f8ec
63870b6
dd3f8ec
 
 
63870b6
f899730
 
a1ac20f
63870b6
a1ac20f
63870b6
 
adab8e7
 
93c3eaa
63870b6
 
 
 
f899730
8086716
 
63870b6
 
 
 
 
 
93c3eaa
 
f899730
 
 
 
8086716
63870b6
 
93c3eaa
f899730
63870b6
adab8e7
63870b6
f899730
adab8e7
 
63870b6
adab8e7
63870b6
f899730
63870b6
adab8e7
 
f899730
adab8e7
63870b6
 
adab8e7
63870b6
f899730
adab8e7
63870b6
 
adab8e7
 
 
f899730
adab8e7
63870b6
 
adab8e7
63870b6
adab8e7
63870b6
 
 
 
adab8e7
63870b6
 
 
f899730
 
adab8e7
93c3eaa
adab8e7
993fdee
 
 
 
93c3eaa
f899730
 
 
adab8e7
f899730
93c3eaa
63870b6
93c3eaa
 
63870b6
93c3eaa
 
8086716
93c3eaa
 
8086716
f899730
 
 
8086716
 
 
 
 
 
 
 
 
 
 
f899730
8086716
 
 
 
63870b6
 
 
1de2c2c
f899730
 
 
63870b6
8086716
adab8e7
 
 
 
f899730
 
63870b6
8086716
 
 
 
 
adab8e7
f899730
adab8e7
f899730
adab8e7
8086716
 
adab8e7
8086716
adab8e7
8086716
 
adab8e7
 
f899730
 
adab8e7
8086716
 
63870b6
8086716
 
adab8e7
f899730
adab8e7
f899730
adab8e7
63870b6
8086716
adab8e7
63870b6
8086716
 
 
 
993fdee
63870b6
8086716
adab8e7
8086716
adab8e7
63870b6
f899730
 
 
63870b6
f899730
8086716
63870b6
f899730
8086716
f899730
 
 
adab8e7
f899730
adab8e7
8086716
 
 
 
 
adab8e7
f899730
adab8e7
f899730
8086716
 
adab8e7
8086716
 
 
adab8e7
 
f899730
 
8086716
 
 
f899730
 
adab8e7
f899730
8086716
 
adab8e7
8086716
 
adab8e7
 
f899730
 
8086716
 
63870b6
 
f899730
63870b6
 
adab8e7
f899730
adab8e7
 
f899730
adab8e7
63870b6
f899730
63870b6
adab8e7
f899730
adab8e7
63870b6
 
 
 
 
 
adab8e7
63870b6
f899730
adab8e7
f899730
adab8e7
8086716
63870b6
adab8e7
63870b6
 
adab8e7
63870b6
 
 
 
 
 
 
 
adab8e7
993fdee
adab8e7
53f194a
adab8e7
f899730
 
8086716
93c3eaa
adab8e7
63870b6
 
f899730
8086716
 
63870b6
 
 
 
92f504c
 
adab8e7
93c3eaa
92f504c
adab8e7
 
93c3eaa
92f504c
 
 
 
 
 
 
 
 
 
 
 
63870b6
 
 
 
 
 
8086716
f899730
8086716
adab8e7
f899730
8086716
adab8e7
 
8086716
adab8e7
 
 
 
8086716
f899730
adab8e7
f899730
adab8e7
 
 
 
 
 
 
f899730
adab8e7
 
 
f899730
adab8e7
 
 
 
63870b6
 
f899730
8086716
63870b6
 
 
8086716
adab8e7
 
 
 
f899730
adab8e7
f899730
 
 
 
adab8e7
8086716
adab8e7
 
63870b6
 
adab8e7
63870b6
 
 
 
 
 
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
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { StateManager, initDB } from './stateManager.js';
import { AIEngine } from './aiEngine.js';
import fs from 'fs';
import admin from 'firebase-admin';
import crypto from "crypto";

// --- FIREBASE SETUP ---
let db = null;
let firestore = null;
let storage = null;

try {
    if (process.env.FIREBASE_SERVICE_ACCOUNT_JSON) {
        const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT_JSON);
        
        // Specific bucket as requested
        const bucketName = `shago-web.firebasestorage.app`; 

        if (admin.apps.length === 0) {
            admin.initializeApp({
                credential: admin.credential.cert(serviceAccount),
                databaseURL: "https://shago-web-default-rtdb.firebaseio.com", 
                storageBucket: bucketName
            });
        }
        
        db = admin.database();
        firestore = admin.firestore();
        storage = admin.storage();
        
        initDB(db);
        console.log("🔥 Firebase Connected (RTDB, Firestore, Storage) & StateManager Linked");
    } else {
        console.warn("⚠️ Memory-Only mode.");
    }
} catch (e) { console.error("Firebase Init Error:", e); }


const app = express();
const PORT = process.env.PORT || 7860;

// ---
/*

app.use((req, res, next) => {
  console.log('[REQ]', req.method, req.originalUrl);
  console.log('[HEADERS]', req.headers);
  console.log('[BODY]', req.body ?? '(unparseable or empty)');
  next();
});

*/

// ---


// Load prompts safely
let sysPrompts = {};
try {
    sysPrompts = JSON.parse(fs.readFileSync('./prompts.json', 'utf8'));
} catch (e) {
    console.error("Failed to load prompts.json:", e);
}

app.use(cors());
app.use(bodyParser.json({ limit: '50mb' }));

// --- CREDIT CONFIGURATION ---

// Minimums required to start a request
const MIN_BASIC_REQUIRED = 50; 
const MIN_DIAMOND_REQUIRED = 50; 

// Fixed cost for images (Basic credits)
const IMAGE_COST_BASIC = 1000; 

/**
 * Checks if user has enough credits of a specific type.
 * @param {string} userId 
 * @param {'basic'|'diamond'} type 
 */
async function checkMinimumCredits(userId, type = 'basic') {
    if (!db) return; 

    // Path: users/{uid}/credits/basic OR users/{uid}/credits/diamond
    const snap = await db.ref(`users/${userId}/credits/${type}`).once('value');
    const credits = snap.val() || 0;

    const required = type === 'diamond' ? MIN_DIAMOND_REQUIRED : MIN_BASIC_REQUIRED;

    if (credits < required) {
      
        res.status(500).json({ 
          insufficient: true,
          error:`Insufficient ${type} credits. You have ${credits}, need minimum ${required} to proceed.`
   
        });
        // throw new Error(`Insufficient ${type} credits. You have ${credits}, need minimum ${required} to proceed.`);
    }
}

/**
 * Deducts exact tokens from the user's specific wallet.
 * @param {string} userId 
 * @param {number} amount 
 * @param {'basic'|'diamond'} type 
 */
async function deductUserCredits(userId, amount, type = 'basic') {
    if (!db || !amount || amount <= 0) return;
    
    try {
        const ref = db.ref(`users/${userId}/credits/${type}`);
        await ref.transaction((current_credits) => {
            const current = current_credits || 0;
            return Math.max(0, current - amount);
        });
        console.log(`[Credits] Deducted ${amount} ${type} credits from User ${userId}`);
    } catch (err) {
        console.error(`[Credits] Failed to deduct ${amount} ${type} from ${userId}:`, err);
    }
}

// --- MIDDLEWARE ---

const validateRequest = (req, res, next) => {
    if (req.path.includes('/admin/cleanup')) return next();
    
    const { userId, projectId } = req.body;
    
    // Ensure userId exists for credit checks
    if (!userId && (req.path.includes('/onboarding') || req.path.includes('/new') || req.path.includes('/project'))) {
        return res.status(400).json({ error: "Missing userId" });
    }
    
    next();
};

function extractWorkerPrompt(text) {
    const match = text.match(/WORKER_PROMPT:\s*(.*)/s);
    return match ? match[1].trim() : null;
}

function formatContext({ hierarchyContext, scriptContext, logContext }) {
    let out = "";
    if (scriptContext) out += `\n[TARGET SCRIPT]: ${scriptContext.targetName}\n[SOURCE PREVIEW]: ${scriptContext.scriptSource?.substring(0, 1000)}...`;
    if (logContext) out += `\n[LAST LOGS]: ${logContext.logs}`;
    return out;
}

function extractPMQuestion(text) {
    const match = text.match(/\[ASK_PM:\s*(.*?)\]/s); 
    return match ? match[1].trim() : null;
}

function extractImagePrompt(text) {
    const match = text.match(/\[GENERATE_IMAGE:\s*(.*?)\]/s);
    return match ? match[1].trim() : null;
}

// --- ADMIN ENDPOINTS ---

app.get('/admin/cleanup', async (req, res) => {
    try {
        const removed = StateManager.cleanupMemory();
        res.json({ success: true, removedCount: removed });
    } catch (err) {
        res.status(500).json({ error: "Cleanup failed" });
    }
});

// --- ONBOARDING ENDPOINTS ---

app.post('/onboarding/analyze', validateRequest, async (req, res) => {
    const { description, userId } = req.body;
  
    if (!description) return res.status(400).json({ error: "Description required" });

    try {
        // Analyst uses BASIC models (Flash)
        await checkMinimumCredits(userId, 'basic');

        console.log(`[Onboarding] Analyzing idea...`);
        
        const result = await AIEngine.generateEntryQuestions(description);
        
        const usage = result.usage?.totalTokenCount || 0;

        // Bill Basic
        if (usage > 0) await deductUserCredits(userId, usage, 'basic');

        if (result.status === "REJECTED") {
            return res.json({ 
                rejected: true, 
                reason: result.reason || "Idea violates TOS." 
            });
        }
        res.json({ questions: result.questions });

    } catch (err) {
        console.error(err);
        if (err.message.includes("Insufficient")) {
            return res.status(402).json({ error: err.message });
        }
        res.status(500).json({ error: "Analysis failed" });
    }
});

app.post('/onboarding/create', validateRequest, async (req, res) => {
    const { userId, description, answers } = req.body;
    let basicTokens = 0; // Create flow uses Grader (Basic) + Image (Basic)

    try {
        // Pre-flight check
        await checkMinimumCredits(userId, 'basic');

        const randomHex = (n = 6) => crypto.randomBytes(Math.ceil(n/2)).toString("hex").slice(0, n);
        const projectId = `proj_${Date.now()}_${randomHex(7)}`;

        console.log(`[Onboarding] Grading Project ${projectId}...`);

        // 1. Grading (Basic)
        const gradingResult = await AIEngine.gradeProject(description, answers);
        basicTokens += (gradingResult.usage?.totalTokenCount || 0);

        const isFailure = gradingResult.feasibility < 30 || gradingResult.rating === 'F';

        let thumbnailBase64 = null;

        if (!isFailure) {
            console.log(`[Onboarding] ✅ Passed. Generating Thumbnail...`);
            const imagePrompt = `Game Title: ${gradingResult.title}. Core Concept: ${description}`;
            
            // 2. Image Generation (Basic)
            const imgResult = await AIEngine.generateImage(imagePrompt);
            if (imgResult) {
                thumbnailBase64 = imgResult.image;
                // Add token usage for text + fixed cost
                basicTokens += (imgResult.usage || 0); 
                if (imgResult.image) basicTokens += IMAGE_COST_BASIC;
            }
        }

        // Upload Logic
        let thumbnailUrl = null;
        if (thumbnailBase64 && storage) {
            try {
                const base64Data = thumbnailBase64.replace(/^data:image\/\w+;base64,/, "");
                const buffer = Buffer.from(base64Data, 'base64');
                const bucket = storage.bucket();
                const file = bucket.file(`${projectId}/thumbnail.png`);
                await file.save(buffer, { metadata: { contentType: 'image/png' } });
                await file.makePublic();
                thumbnailUrl = `https://storage.googleapis.com/${bucket.name}/${projectId}/thumbnail.png`;
            } catch (uploadErr) {
                console.error("Storage Upload Failed:", uploadErr);
            }
        }

        const timestamp = Date.now();
        const status = isFailure ? "rejected" : "Idle";

        // Save Data Logic
        if (!isFailure) {
            const memoryObject = {
                id: projectId,
                userId,
                title: gradingResult.title || "Untitled",
                description,
                answers,
                stats: gradingResult,
                thumbnail: thumbnailUrl, 
                createdAt: timestamp,
                status,
                workerHistory: [],
                pmHistory: [],
                commandQueue: [],
                failureCount: 0
            };
            await StateManager.updateProject(projectId, memoryObject);
        }

        if (firestore && !isFailure) {
            await firestore.collection('projects').doc(projectId).set({
                id: projectId,
                userId: userId,
                assets: thumbnailUrl ? [thumbnailUrl] : [],
                createdAt: admin.firestore.FieldValue.serverTimestamp()
            });
        }

        if (db && !isFailure) {
            const updates = {};
            updates[`projects/${projectId}/info`] = {
                id: projectId,
                userId,
                title: gradingResult.title || "Untitled",
                description,
                answers,
                stats: gradingResult,
                createdAt: timestamp,
                status
            };
            if (thumbnailUrl) updates[`projects/${projectId}/thumbnail`] = { url: thumbnailUrl };
            updates[`projects/${projectId}/state`] = {
                workerHistory: [],
                pmHistory: [],
                commandQueue: [],
                failureCount: 0
            };
            await db.ref().update(updates);
        }

        // Deduct Basic Credits
        if (basicTokens > 0) await deductUserCredits(userId, basicTokens, 'basic');
       console.log("sending");
        res.json({ 
          status: 200,
            success: !isFailure, 
            projectId, 
            stats: gradingResult, 
            title: gradingResult.title || "Untitled",
            thumbnail: thumbnailBase64
        });

    } catch (err) {
        console.error("Create Error:", err);
        if (err.message.includes("Insufficient")) {
            return res.status(402).json({ error: err.message });
        }
        res.status(500).json({ error: "Creation failed" });
    }
});

// --- CORE ENDPOINTS ---

async function runBackgroundInitialization(projectId, userId, description) {
    console.log(`[Background] Starting initialization for ${projectId}`);
    
    // Separate Counters
    let diamondUsage = 0; // For PM
    let basicUsage = 0;   // For Worker

    try {
        const pmHistory = [];
        
        // 1. Generate GDD (PM -> Diamond)
        const gddPrompt = `Create a comprehensive GDD for: ${description}`;
        const gddResult = await AIEngine.callPM(pmHistory, gddPrompt);
        
        diamondUsage += (gddResult.usage?.totalTokenCount || 0);
        const gddText = gddResult.text;

        pmHistory.push({ role: 'user', parts: [{ text: gddPrompt }] });
        pmHistory.push({ role: 'model', parts: [{ text: gddText }] });

        // 2. Generate First Task (PM -> Diamond)
        const taskPrompt = "Based on the GDD, generate the first technical milestone.\nOutput format:\nTASK_NAME: <Name>\nWORKER_PROMPT: <Specific, isolated instructions for the worker>";
        const taskResult = await AIEngine.callPM(pmHistory, taskPrompt);
        
        diamondUsage += (taskResult.usage?.totalTokenCount || 0);
        const taskText = taskResult.text;

        pmHistory.push({ role: 'user', parts: [{ text: taskPrompt }] });
        pmHistory.push({ role: 'model', parts: [{ text: taskText }] });

        // 3. Initialize Worker (Worker -> Basic)
        const initialWorkerInstruction = extractWorkerPrompt(taskText) || `Initialize structure for: ${description}`;
        const workerHistory = [];
        const initialWorkerPrompt = `CONTEXT: New Project. \nINSTRUCTION: ${initialWorkerInstruction}`;
        
        const workerResult = await AIEngine.callWorker(workerHistory, initialWorkerPrompt, []);
        
        basicUsage += (workerResult.usage?.totalTokenCount || 0);
        const workerText = workerResult.text;

        workerHistory.push({ role: 'user', parts: [{ text: initialWorkerPrompt }] });
        workerHistory.push({ role: 'model', parts: [{ text: workerText }] });

        // 4. Update Memory
        await StateManager.updateProject(projectId, {
            userId,
            pmHistory,
            workerHistory,
            gdd: gddText,
            failureCount: 0
        });

        // 5. Queue commands (Handle assets + basic costs)
        // We pass userId to deduct image costs (Basic) immediately inside this function
        await processAndQueueResponse(projectId, workerText, userId); 
        
        // 6. Update Status
        if(db) await db.ref(`projects/${projectId}/info`).update({
            status: "IDLE",
            lastUpdated: Date.now()
        });
        
        // 7. Deduct Accumulated Credits
        if (diamondUsage > 0) await deductUserCredits(userId, diamondUsage, 'diamond');
        if (basicUsage > 0) await deductUserCredits(userId, basicUsage, 'basic');
        
        console.log(`[Background] Init complete. Diamond: ${diamondUsage}, Basic: ${basicUsage}`);

    } catch (err) {
        console.error(`[Background] Init Error for ${projectId}:`, err);
        if(db) await db.ref(`projects/${projectId}/info/status`).set("error");
    }
}

app.post('/new/project', validateRequest, async (req, res) => {
    const { userId, projectId, description } = req.body;
    
    try {
        // Init requires BOTH types to be safe
        await checkMinimumCredits(userId, 'diamond');
        await checkMinimumCredits(userId, 'basic');

        if(db) db.ref(`projects/${projectId}/info/status`).set("initializing");
        
        res.json({ 
            success: true, 
            message: "Project initialization started in background."
        });

        runBackgroundInitialization(projectId, userId, description);

    } catch (err) {
        if (err.message.includes("Insufficient")) {
            return res.status(402).json({ error: err.message });
        }
        res.status(500).json({ error: "Failed to start project" });
    }
});

app.post('/project/feedback', async (req, res) => {
    const { userId, projectId, prompt, hierarchyContext, scriptContext, logContext, taskComplete, images } = req.body;
    
    let diamondUsage = 0;
    let basicUsage = 0;
    
    try {
        const project = await StateManager.getProject(projectId);
        if (!project) return res.status(404).json({ error: "Project not found." });
        if (project.userId !== userId) return res.status(403).json({ error: "Unauthorized" });

        // Basic Check (most interaction is worker)
        await checkMinimumCredits(userId, 'basic');
        
        if(db) await db.ref(`projects/${projectId}/info/status`).set("working");
          
        if (taskComplete) {
            console.log(`[${projectId}] ✅ TASK COMPLETE.`);
            const summary = `Worker completed the previous task. Logs: ${logContext?.logs || "Clean"}. \nGenerate the NEXT task using 'WORKER_PROMPT:' format.`;
            
            // PM Call -> Diamond
            const pmResult = await AIEngine.callPM(project.pmHistory, summary);
            diamondUsage += (pmResult.usage?.totalTokenCount || 0);
            const pmText = pmResult.text;
            
            project.pmHistory.push({ role: 'user', parts: [{ text: summary }] });
            project.pmHistory.push({ role: 'model', parts: [{ text: pmText }] });

            const nextInstruction = extractWorkerPrompt(pmText);
            if (!nextInstruction) {
                 await StateManager.updateProject(projectId, { pmHistory: project.pmHistory, status: "IDLE" });
                 if(db) await db.ref(`projects/${projectId}/info`).update({ status: "IDLE", lastUpdated: Date.now() });
                 
                 // Deduct what we used
                 if (diamondUsage > 0) await deductUserCredits(userId, diamondUsage, 'diamond');
                 
                 return res.json({ success: true, message: "No further tasks. Project Idle." });
            }

            const newWorkerHistory = [];
            const newPrompt = `New Objective: ${nextInstruction}`;
            
            // Worker Call -> Basic
            const workerResult = await AIEngine.callWorker(newWorkerHistory, newPrompt, []);
            basicUsage += (workerResult.usage?.totalTokenCount || 0);
            const workerText = workerResult.text;

            newWorkerHistory.push({ role: 'user', parts: [{ text: newPrompt }] });
            newWorkerHistory.push({ role: 'model', parts: [{ text: workerText }] });

            await StateManager.updateProject(projectId, {
                pmHistory: project.pmHistory,
                workerHistory: newWorkerHistory,
                failureCount: 0
            });

            StateManager.queueCommand(projectId, { type: "EXECUTE", payload: "warn('Starting Next Task...')" });
            await processAndQueueResponse(projectId, workerText, userId);
            
            if(db) await db.ref(`projects/${projectId}/info`).update({ status: "working", lastUpdated: Date.now() });

            // Final Bill
            if (diamondUsage > 0) await deductUserCredits(userId, diamondUsage, 'diamond');
            if (basicUsage > 0) await deductUserCredits(userId, basicUsage, 'basic');

            return res.json({ success: true, message: "Next Task Assigned" });
        }

        // Logic for Failure Handling (PM Guidance)
        if (project.failureCount > 3) {
            const pmPrompt = (sysPrompts.pm_guidance_prompt || "Analyze logs: {{LOGS}}").replace('{{LOGS}}', logContext?.logs);
            
            // PM -> Diamond
            const pmResult = await AIEngine.callPM(project.pmHistory, pmPrompt);
            diamondUsage += (pmResult.usage?.totalTokenCount || 0);
            const pmVerdict = pmResult.text;

            if (pmVerdict.includes("[TERMINATE]")) {
                const fixInstruction = pmVerdict.replace("[TERMINATE]", "").trim();
                const resetHistory = [];
                const resetPrompt = `[SYSTEM]: Previous worker terminated. \nNew Objective: ${fixInstruction}`;
                
                // Worker -> Basic
                const workerResult = await AIEngine.callWorker(resetHistory, resetPrompt, []);
                basicUsage += (workerResult.usage?.totalTokenCount || 0);
                
                resetHistory.push({ role: 'user', parts: [{ text: resetPrompt }] });
                resetHistory.push({ role: 'model', parts: [{ text: workerResult.text }] });

                await StateManager.updateProject(projectId, { workerHistory: resetHistory, failureCount: 0 });
                StateManager.queueCommand(projectId, { type: "EXECUTE", payload: "print('SYSTEM: Worker Reset')" });
                await processAndQueueResponse(projectId, workerResult.text, userId);
                
                if (diamondUsage > 0) await deductUserCredits(userId, diamondUsage, 'diamond');
                if (basicUsage > 0) await deductUserCredits(userId, basicUsage, 'basic');
                return res.json({ success: true, message: "Worker Terminated." });
            } else {
                const injection = `[PM GUIDANCE]: ${pmVerdict} \n\nApply this fix now.`;
                
                // Worker -> Basic
                const workerResult = await AIEngine.callWorker(project.workerHistory, injection, []);
                basicUsage += (workerResult.usage?.totalTokenCount || 0);

                project.workerHistory.push({ role: 'user', parts: [{ text: injection }] });
                project.workerHistory.push({ role: 'model', parts: [{ text: workerResult.text }] });
                
                await StateManager.updateProject(projectId, { workerHistory: project.workerHistory, failureCount: 1 });
                await processAndQueueResponse(projectId, workerResult.text, userId);
                
                if (diamondUsage > 0) await deductUserCredits(userId, diamondUsage, 'diamond');
                if (basicUsage > 0) await deductUserCredits(userId, basicUsage, 'basic');
                return res.json({ success: true, message: "PM Guidance Applied." });
            }
        }

        // Standard Interaction (Worker Only = Basic)
        const fullInput = `USER: ${prompt || "Automatic Feedback"}` + formatContext({ hierarchyContext, scriptContext, logContext });
        
        let workerResult = await AIEngine.callWorker(project.workerHistory, fullInput, images || []);
        basicUsage += (workerResult.usage?.totalTokenCount || 0);
        let responseText = workerResult.text;
        
        // PM Consultation Check
        const pmQuestion = extractPMQuestion(responseText);
        if (pmQuestion) {
            // PM -> Diamond
            const pmConsultPrompt = `[WORKER CONSULTATION]: The Worker asks: "${pmQuestion}"\nProvide a technical answer to unblock them.`;
            const pmResult = await AIEngine.callPM(project.pmHistory, pmConsultPrompt);
            diamondUsage += (pmResult.usage?.totalTokenCount || 0);
            const pmAnswer = pmResult.text;

            project.pmHistory.push({ role: 'user', parts: [{ text: pmConsultPrompt }] });
            project.pmHistory.push({ role: 'model', parts: [{ text: pmAnswer }] });

            const injectionMsg = `[PM RESPONSE]: ${pmAnswer}`;
            project.workerHistory.push({ role: 'user', parts: [{ text: fullInput }] });
            project.workerHistory.push({ role: 'model', parts: [{ text: responseText }] });
            
            // Re-call Worker -> Basic
            workerResult = await AIEngine.callWorker(project.workerHistory, injectionMsg, []);
            basicUsage += (workerResult.usage?.totalTokenCount || 0);
            responseText = workerResult.text;

            project.workerHistory.push({ role: 'user', parts: [{ text: injectionMsg }] });
            project.workerHistory.push({ role: 'model', parts: [{ text: responseText }] });
        } else {
            project.workerHistory.push({ role: 'user', parts: [{ text: fullInput }] });
            project.workerHistory.push({ role: 'model', parts: [{ text: responseText }] });
        }

        await StateManager.updateProject(projectId, { 
            workerHistory: project.workerHistory,
            pmHistory: project.pmHistory, 
            failureCount: project.failureCount 
        });
        
        await processAndQueueResponse(projectId, responseText, userId);
        
        if(db) await db.ref(`projects/${projectId}/info`).update({ status: "idle", lastUpdated: Date.now() });
      
        // Final Billing
        if (diamondUsage > 0) await deductUserCredits(userId, diamondUsage, 'diamond');
        if (basicUsage > 0) await deductUserCredits(userId, basicUsage, 'basic');

        res.json({ success: true });

    } catch (err) {
        console.error("AI Error:", err);
        if (err.message.includes("Insufficient")) {
            return res.status(402).json({ error: err.message });
        }
        res.status(500).json({ error: "AI Failed" });
    }
});

app.post('/project/ping', async (req, res) => {
    const { projectId, userId } = req.body;
    if (!projectId || !userId) return res.status(400).json({ error: "Missing ID fields" });
    
    const project = await StateManager.getProject(projectId);
    if (!project) return res.status(404).json({ action: "IDLE", error: "Project not found" });
    if (project.userId !== userId) return res.status(403).json({ error: "Unauthorized" });

    const command = await StateManager.popCommand(projectId);
    
    if (command) {
        if (command.payload === "CLEAR_CONSOLE") {
             res.json({ action: "CLEAR_LOGS" });
        } else {
            res.json({ 
                action: command.type, 
                target: command.payload, 
                code: command.type === 'EXECUTE' ? command.payload : null 
            });
        }
    } else {
        res.json({ action: "IDLE" });
    }
});

app.post('/human/override', validateRequest, async (req, res) => {
    const { projectId, instruction, pruneHistory, userId } = req.body;
    let basicUsage = 0;

    try {
        await checkMinimumCredits(userId, 'basic');

        const project = await StateManager.getProject(projectId);
        const overrideMsg = `[SYSTEM OVERRIDE]: ${instruction}`;

        if (pruneHistory && project.workerHistory.length >= 2) {
            project.workerHistory.pop();
            project.workerHistory.pop();
        }

        // Worker -> Basic
        const workerResult = await AIEngine.callWorker(project.workerHistory, overrideMsg, []);
        basicUsage += (workerResult.usage?.totalTokenCount || 0);

        project.workerHistory.push({ role: 'user', parts: [{ text: overrideMsg }] });
        project.workerHistory.push({ role: 'model', parts: [{ text: workerResult.text }] });
        
        await StateManager.updateProject(projectId, { workerHistory: project.workerHistory });
        await processAndQueueResponse(projectId, workerResult.text, userId);
        
        if (basicUsage > 0) await deductUserCredits(userId, basicUsage, 'basic');
        
        res.json({ success: true });
    } catch (err) {
        if (err.message.includes("Insufficient")) {
            return res.status(402).json({ error: err.message });
        }
        res.status(500).json({ error: "Override Failed" });
    }
});

// Helper to handle Asset Parsing & Billing (Basic Credits)
async function processAndQueueResponse(projectId, rawResponse, userId) {
    const imgPrompt = extractImagePrompt(rawResponse);
    if (imgPrompt) {
        console.log(`[${projectId}] 🎨 Generating Asset: ${imgPrompt}`);
        
        // 1. Generate Image (returns { image, usage } or null)
        const imgResult = await AIEngine.generateImage(imgPrompt);
        
        if (imgResult && imgResult.image) {
            // 2. Bill for image tokens immediately (Basic)
            const imgTokens = imgResult.usage?.totalTokenCount || 0;
            const totalCost = imgTokens; // imgTokens + IMAGE_COST_BASIC;
            
            if (userId && totalCost > 0) {
                await deductUserCredits(userId, totalCost, 'basic');
            }

            // 3. Queue creation command
            await StateManager.queueCommand(projectId, { type: "CREATE_ASSET", payload: imgResult.image });
        }
    }
    // Queue the raw text response for the frontend
    await StateManager.queueCommand(projectId, rawResponse);
}

app.listen(PORT, () => {
    console.log(`AI Backend Running on ${PORT}`);
});