File size: 35,428 Bytes
7102d02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434ea69
 
 
2a67f07
 
7102d02
434ea69
2a67f07
 
 
 
 
7102d02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5092b90
 
 
 
 
7102d02
 
 
 
 
 
 
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
from flask import Flask, request, jsonify, send_from_directory
import firebase_admin
from firebase_admin import credentials, db
import requests
import os
import json
from datetime import datetime
from sentence_transformers import SentenceTransformer
import uuid
import re
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

# Try to load llama-cpp-python (GGUF support)
try:
    from llama_cpp import Llama
    LLAMA_AVAILABLE = True
except ImportError:
    LLAMA_AVAILABLE = False
    print("⚠️ llama-cpp-python not installed. Llama fallback unavailable.")

app = Flask(__name__)

# ---------- Firebase ----------
firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
if not firebase_service_account_json:
    raise ValueError("FIREBASE_SERVICE_ACCOUNT secret missing")
service_account_info = json.loads(firebase_service_account_json)
database_url = "https://chat-bot-80c6e-default-rtdb.firebaseio.com/"
cred = credentials.Certificate(service_account_info)
firebase_admin.initialize_app(cred, {'databaseURL': database_url})
ref = firebase_admin.db.reference('/')
print("✅ Firebase connected")

# ---------- Sentence-Transformer ----------
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
print("✅ Embedding model loaded")

# ---------- Load Llama 3.2 1B GGUF (if available) ----------
llama_model = None
llama_path = os.getenv("LLAMA_GGUF_PATH")
if LLAMA_AVAILABLE and llama_path and os.path.exists(llama_path):
    try:
        llama_model = Llama(model_path=llama_path, n_ctx=2048, n_threads=2, verbose=False)
        print("✅ Llama 3.2 1B GGUF loaded (fallback)")
    except Exception as e:
        print(f"⚠️ Failed to load Llama GGUF: {e}")
else:
    print("⚠️ Llama GGUF not configured – will use GPT‑2 fallback if available")

# ---------- Load GPT‑2 (final fallback) ----------
gpt_model = None
gpt_tokenizer = None
if not llama_model:
    try:
        gpt_tokenizer = AutoTokenizer.from_pretrained("gpt2")
        gpt_model = AutoModelForCausalLM.from_pretrained("gpt2")
        gpt_tokenizer.pad_token = gpt_tokenizer.eos_token
        if torch.cuda.is_available():
            gpt_model = gpt_model.to("cuda")
        print("✅ GPT‑2 loaded (final fallback)")
    except Exception as e:
        print(f"⚠️ GPT‑2 load failed: {e}")

# ---------- AI Call (Groq → Owl Alpha → Gemini → Llama GGUF → GPT‑2 → rule) ----------
def call_ai(prompt):
    # 1. Groq (fast, free)
    groq_key = os.getenv("GROQ_API_KEY")
    if groq_key:
        url = "https://api.groq.com/openai/v1/chat/completions"
        headers = {"Authorization": f"Bearer {groq_key}", "Content-Type": "application/json"}
        payload = {
            "model": "llama3-8b-8192",
            "messages": [{"role": "user", "content": prompt}],
            "temperature": 0.7,
            "max_tokens": 150
        }
        try:
            resp = requests.post(url, json=payload, headers=headers, timeout=10)
            if resp.status_code == 200:
                return resp.json()["choices"][0]["message"]["content"].strip()
        except Exception as e:
            print(f"Groq error: {e}")

    # 2. OpenRouter Owl Alpha (primary – free, 1M context)
    openrouter_key = os.getenv("OPENROUTER_API_KEY")
    if openrouter_key:
        url = "https://openrouter.ai/api/v1/chat/completions"
        headers = {"Authorization": f"Bearer {openrouter_key}", "Content-Type": "application/json"}
        payload = {
            "model": "openrouter/owl-alpha",
            "messages": [{"role": "user", "content": prompt}],
            "temperature": 0.7,
            "max_tokens": 150
        }
        try:
            resp = requests.post(url, json=payload, headers=headers, timeout=10)
            if resp.status_code == 200:
                return resp.json()["choices"][0]["message"]["content"].strip()
        except Exception as e:
            print(f"Owl Alpha error: {e}")

    # 3. OpenRouter Gemini (fallback)
    if openrouter_key:
        url = "https://openrouter.ai/api/v1/chat/completions"
        headers = {"Authorization": f"Bearer {openrouter_key}", "Content-Type": "application/json"}
        payload = {
            "model": "google/gemini-2.0-flash-lite-preview-02-05",
            "messages": [{"role": "user", "content": prompt}],
            "temperature": 0.7,
            "max_tokens": 150
        }
        try:
            resp = requests.post(url, json=payload, headers=headers, timeout=10)
            if resp.status_code == 200:
                return resp.json()["choices"][0]["message"]["content"].strip()
        except Exception as e:
            print(f"Gemini error: {e}")

    # 4. Llama 3.2 1B GGUF (local)
    if llama_model:
        try:
            output = llama_model.create_chat_completion(
                messages=[{"role": "user", "content": prompt}],
                temperature=0.7,
                max_tokens=150
            )
            return output["choices"][0]["message"]["content"].strip()
        except Exception as e:
            print(f"Llama GGUF error: {e}")

    # 5. GPT‑2 fallback
    if gpt_model is not None:
        try:
            inputs = gpt_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024)
            if torch.cuda.is_available():
                inputs = {k: v.to("cuda") for k, v in inputs.items()}
            outputs = gpt_model.generate(
                **inputs,
                max_new_tokens=120,
                do_sample=True,
                temperature=0.7,
                repetition_penalty=1.2,
                pad_token_id=gpt_tokenizer.eos_token_id
            )
            response = gpt_tokenizer.decode(outputs[0], skip_special_tokens=True)
            if response.startswith(prompt):
                response = response[len(prompt):].strip()
            return response if response else "What else would you like to share about your project?"
        except Exception as e:
            print(f"GPT‑2 error: {e}")

    # 6. Ultimate rule‑based
    return "What else would you like to share about your project?"

# ---------- Helper: Load extra services from Firebase ----------
def get_extra_services():
    snap = ref.child("extra_services").get()
    if not snap:
        default = {
            "live_chat": {"name": "live chat", "price": 20000, "timeline": 3, "display": "Live Chat (+PKR 20,000, +3 days)"},
            "booking_system": {"name": "booking system", "price": 35000, "timeline": 5, "display": "Booking System (+PKR 35,000, +5 days)"},
            "multi_language": {"name": "multi-language", "price": 25000, "timeline": 4, "display": "Multi-Language (+PKR 25,000, +4 days)"},
            "custom_backend": {"name": "custom backend", "price": 100000, "timeline": 15, "display": "Custom Backend (+PKR 1,00,000, +15 days)"}
        }
        ref.child("extra_services").set(default)
        return default
    return snap

# ---------- Pricing Helpers ----------
BASE_PRICE = 50000
BASE_PAGES = 5
EXTRA_PAGE_PRICE = 5000
BASE_TIMELINE = 10

def calculate_price_and_timeline(req):
    extra_services = get_extra_services()
    pages = req.get("pages", 5)
    domain = req.get("domain", False)
    ecommerce = req.get("ecommerce", False)
    chatbot = req.get("chatbot", False)
    seo = req.get("seo", False)
    extra_features = req.get("extra_features", [])
    inventory = req.get("inventory", "").lower() == "yes"
    database = req.get("data", "").lower() == "yes"

    price = BASE_PRICE
    timeline = BASE_TIMELINE
    if pages > BASE_PAGES:
        price += (pages - BASE_PAGES) * EXTRA_PAGE_PRICE
        timeline += (pages - BASE_PAGES)
    if domain:
        price += 5000
        timeline += 1
    if ecommerce:
        price += 50000
        timeline += 10
    if chatbot:
        price += 30000
        timeline += 5
    if seo:
        price += 25000
        timeline += 5
    for feat in extra_features:
        if feat in extra_services:
            info = extra_services[feat]
            price += info.get("price", 0)
            timeline += info.get("timeline", 0)
    if inventory:
        price += 30000
        timeline += 5
    if database:
        price += 40000
        timeline += 8
    return price, timeline

def generate_project_id():
    return f"PROJ-{int(datetime.now().timestamp())}-{uuid.uuid4().hex[:6].upper()}"

def create_project(session_id, requirements):
    project_id = generate_project_id()
    price, timeline = calculate_price_and_timeline(requirements)
    project_data = {
        "project_id": project_id,
        "session_id": session_id,
        "requirements": requirements,
        "calculated_price": price,
        "calculated_timeline": timeline,
        "status": "pending",
        "admin_message": "",
        "created_at": datetime.now().isoformat(),
        "updated_at": datetime.now().isoformat()
    }
    ref.child(f"projects/{project_id}").set(project_data)
    return project_id, price, timeline

def get_project(project_id):
    return ref.child(f"projects/{project_id}").get()

def update_project_status(project_id, status, decline_reason=None):
    data = {"status": status, "updated_at": datetime.now().isoformat()}
    if decline_reason:
        data["admin_message"] = decline_reason
    ref.child(f"projects/{project_id}").update(data)

def update_project_message(project_id, message):
    ref.child(f"projects/{project_id}").update({"admin_message": message, "updated_at": datetime.now().isoformat()})

# ---------- IP & Session ----------
def get_client_ip():
    if request.headers.get('X-Forwarded-For'):
        ip = request.headers.get('X-Forwarded-For').split(',')[0]
    else:
        ip = request.remote_addr
    return ip

def store_ip_for_session(session_id):
    ip = get_client_ip()
    ref.child(f"sessions/{session_id}/ip").set(ip)
    ref.child(f"sessions/{session_id}/last_seen").set(datetime.now().isoformat())

def save_message(session_id, role, content, intent=None):
    ref.child(f"chats/{session_id}/messages").push().set({
        "role": role,
        "content": content,
        "timestamp": datetime.now().isoformat(),
        "intent": intent
    })

def get_chat_history(session_id):
    snap = ref.child(f"chats/{session_id}/messages").order_by_child("timestamp").get()
    if not snap:
        return []
    messages = list(snap.values())
    return sorted(messages, key=lambda x: x.get("timestamp", ""))

# ---------- Step Builder (no auto-add in step answers) ----------
user_sessions = {}

def is_start_project_request(text):
    keywords = ["website banwani", "build website", "new project", "website chahiye", "start project",
                "i want to build a website", "web project", "website banana hai", "naya project"]
    return any(k in text.lower() for k in keywords)

def process_step_by_step(session_id, message):
    msg_lower = message.lower().strip()
    if session_id not in user_sessions:
        if is_start_project_request(message):
            user_sessions[session_id] = {
                "step": "asking_domain",
                "requirements": {},
                "deep_answers": {},
                "deep_index": 0,
                "max_deep_rounds": 2,
                "deep_questions": []
            }
            return "🌐 **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
        return None

    session = user_sessions[session_id]
    step = session.get("step")
    req = session.get("requirements", {})

    def is_valid_domain_answer(ans): return ans.lower() in ["yes", "no", "han", "nahi"]
    def is_valid_pages_answer(ans):
        try:
            return int(ans) >= 1
        except:
            return False
    def is_valid_yes_no(ans): return ans.lower() in ["yes", "no", "han", "nahi"]
    def is_valid_extra_feature_name(ans):
        if ans.lower() in ["none", "done", "no"]: return True
        extra_services = get_extra_services()
        for val in extra_services.values():
            if val.get("name", "").lower() in ans.lower() or ans.lower() in val.get("name", "").lower():
                return True
        return False
    def is_valid_mobile(ans): return re.search(r'\d{10,15}', ans) is not None
    def is_valid_email(ans): return "@" in ans and "." in ans

    # Handle "add more"
    if msg_lower in ["add more", "add something", "extra add"]:
        session["step"] = "asking_extra"
        extra_services = get_extra_services()
        extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
        return f"✨ **Add extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**."

    # Main step handlers (no invoice auto-add here)
    if step == "asking_domain":
        if not is_valid_domain_answer(message):
            return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🌐 Do you need a domain name?"
        req["domain"] = "yes" in msg_lower or "han" in msg_lower
        session["step"] = "asking_pages"
        session["requirements"] = req
        return "📄 **How many pages?** (min 5, extra +PKR 5,000 each)\n\nType a number: **5**, **10**, **15**"

    elif step == "asking_pages":
        if not is_valid_pages_answer(message):
            return "❌ Invalid number. Please enter a valid number of pages (minimum 1).\n\n📄 How many pages?"
        pages = int(re.search(r'\d+', msg_lower).group())
        req["pages"] = max(pages, 5)
        session["step"] = "asking_ecommerce"
        session["requirements"] = req
        return "🛒 **Need e‑commerce?** (payment gateway, cart)\n\nReply: **Yes** or **No**"

    elif step == "asking_ecommerce":
        if not is_valid_yes_no(message):
            return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🛒 Need e‑commerce?"
        req["ecommerce"] = "yes" in msg_lower or "han" in msg_lower
        session["step"] = "asking_chatbot"
        session["requirements"] = req
        return "🤖 **AI chatbot on your website?**\n\nReply: **Yes** or **No**"

    elif step == "asking_chatbot":
        if not is_valid_yes_no(message):
            return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🤖 AI chatbot on your website?"
        req["chatbot"] = "yes" in msg_lower or "han" in msg_lower
        session["step"] = "asking_seo"
        session["requirements"] = req
        return "🔍 **SEO optimization?** (rank on Google)\n\nReply: **Yes** or **No**"

    elif step == "asking_seo":
        if not is_valid_yes_no(message):
            return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🔍 SEO optimization?"
        req["seo"] = "yes" in msg_lower or "han" in msg_lower
        session["step"] = "asking_extra"
        session["requirements"] = req
        extra_services = get_extra_services()
        extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
        return f"✨ **Extra features?**\n\nAvailable:\n{extra_list}\n\nType name (e.g., 'live chat') or **done**."

    elif step == "asking_extra":
        extra_services = get_extra_services()
        if msg_lower in ["none", "done", "no"]:
            session["step"] = "asking_deep"
            session["deep_index"] = 0
            prompt = f"""You are an expert project estimator. Based on the following client requirements, ask the NEXT most important, specific, and open‑ended question to clarify the project details. Do not repeat what has already been answered. Ask about design, content, audience, integrations, or any missing critical detail. Keep your question concise (one sentence).

Current requirements:
{json.dumps(req, indent=2)}

Generated question:"""
            first_q = call_ai(prompt)
            if len(first_q) > 300 or '{' in first_q or '}' in first_q or '```' in first_q:
                first_q = "Could you please provide more details about your target audience or business goals?"
            session["deep_questions"] = [first_q]
            return first_q
        else:
            if not is_valid_extra_feature_name(message):
                available = ', '.join([v['name'] for v in extra_services.values()])
                return f"❌ Sorry, **'{message}'** is not offered. Available: {available}\n\nType a valid name or **done**."
            matched_key = None
            for key, val in extra_services.items():
                if val.get("name", "").lower() in msg_lower or msg_lower in val.get("name", "").lower():
                    matched_key = key
                    break
            if matched_key:
                extra_list = req.get("extra_features", [])
                if matched_key not in extra_list:
                    extra_list.append(matched_key)
                    req["extra_features"] = extra_list
                    session["requirements"] = req
                    # This triggers invoice add in the frontend
                    return f"✅ Added **{extra_services[matched_key]['name']}**.\n\nAny other extras? Type name or **done**."
                else:
                    return f"ℹ️ Already added. Type another name or **done**."
            else:
                return f"❌ Sorry, **'{message}'** is not offered. Available: {', '.join([v['name'] for v in extra_services.values()])}\n\nType a valid name or **done**."

    elif step == "asking_deep":
        idx = session.get("deep_index", 0)
        if idx < session.get("max_deep_rounds", 2):
            if "deep_answers" not in session:
                session["deep_answers"] = {}
            session["deep_answers"][f"deep_{idx}"] = message
            session["deep_index"] = idx + 1
            if idx + 1 < session.get("max_deep_rounds", 2):
                prompt = f"""You are an expert project estimator. Based on the following client requirements and previous answers, ask the NEXT most important, specific, and open‑ended question to clarify the project details. Do not repeat what has already been answered. Keep your question concise (one sentence).

Current requirements:
{json.dumps(req, indent=2)}

Previous deep answers:
{json.dumps(session.get("deep_answers", {}), indent=2)}

Generated question:"""
                next_q = call_ai(prompt)
                if len(next_q) > 300 or '{' in next_q or '}' in next_q or '```' in next_q:
                    next_q = "Is there any specific functionality or integration you consider essential for your project?"
                return next_q
            else:
                session["step"] = "asking_additional"
                session["additional_index"] = 0
                session["additional_questions"] = [
                    {"key": "purpose", "question": "📌 **What is the main purpose of the website?** (e.g., e-commerce store, portfolio, blog, corporate) – Type **skip** to leave blank."},
                    {"key": "theme", "question": "🎨 **Any specific theme or design preference?** (e.g., modern, minimal, colorful, dark) – Type **skip** or describe."},
                    {"key": "content", "question": "📝 **Do you have ready content (text/images)?** Or need us to create? (Type **skip** if not needed now.)"},
                    {"key": "inventory", "question": "📦 **Do you need inventory management?** (For products, stock tracking) – Yes/No or **skip**."},
                    {"key": "data", "question": "🗄️ **Do you need database integration?** (e.g., user accounts, data storage) – Yes/No or **skip**."}
                ]
                return session["additional_questions"][0]["question"]
        else:
            session["step"] = "asking_additional"
            session["additional_index"] = 0
            session["additional_questions"] = [
                {"key": "purpose", "question": "📌 **What is the main purpose of the website?** (e.g., e-commerce store, portfolio, blog, corporate) – Type **skip** to leave blank."},
                {"key": "theme", "question": "🎨 **Any specific theme or design preference?** (e.g., modern, minimal, colorful, dark) – Type **skip** or describe."},
                {"key": "content", "question": "📝 **Do you have ready content (text/images)?** Or need us to create? (Type **skip** if not needed now.)"},
                {"key": "inventory", "question": "📦 **Do you need inventory management?** (For products, stock tracking) – Yes/No or **skip**."},
                {"key": "data", "question": "🗄️ **Do you need database integration?** (e.g., user accounts, data storage) – Yes/No or **skip**."}
            ]
            return session["additional_questions"][0]["question"]

    elif step == "asking_additional":
        idx = session.get("additional_index", 0)
        qlist = session.get("additional_questions", [])
        if idx < len(qlist):
            current_q = qlist[idx]
            key = current_q["key"]
            if "additional_answers" not in session:
                session["additional_answers"] = {}
            if msg_lower in ["skip", "none", "no"]:
                session["additional_answers"][key] = ""
            else:
                session["additional_answers"][key] = message
            session["additional_index"] = idx + 1
            if idx + 1 < len(qlist):
                return qlist[idx+1]["question"]
            else:
                session["step"] = "asking_media"
                return "🖼️ **Do you want to add any additional text or images?** (Reply: Yes/No)\n\nIf Yes, a text area and image upload will appear. Type **skip** if none."
        else:
            session["step"] = "asking_media"
            return "🖼️ **Do you want to add any additional text or images?** (Reply: Yes/No)\n\nIf Yes, a text area and image upload will appear. Type **skip** if none."

    elif step == "asking_media":
        if msg_lower in ["yes", "han"]:
            session["waiting_for_media"] = True
            session["media_text"] = ""
            session["media_image"] = None
            return "MEDIA_REQUEST|Please provide your additional notes in the text area below and/or upload an image.\n\n(After done, type **DONE** to finish.)"
        elif msg_lower in ["no", "skip", "none"]:
            session["step"] = "asking_contact"
            return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
        else:
            return "Please reply **Yes** to add media, **No** to skip."

    elif step == "waiting_media":
        if msg_lower == "done":
            if "media_text" in session and session["media_text"]:
                req["media_text"] = session["media_text"]
            if "media_image" in session and session["media_image"]:
                req["media_image"] = session["media_image"]
            session["requirements"] = req
            session["step"] = "asking_contact"
            del session["waiting_media"]
            return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
        else:
            return "Please type **DONE** when you have finished adding text/image."

    elif step == "asking_contact":
        if "mobile" not in session:
            if not is_valid_mobile(message):
                return "❌ Invalid mobile number. Please enter a valid phone number (10-15 digits).\n\n📞 Please provide your mobile number:"
            session["mobile"] = message
            return "✉️ **Please provide your email address** (e.g., name@example.com) – We'll send the quote and updates."
        else:
            if not is_valid_email(message):
                return "❌ Invalid email address. Please enter a valid email (e.g., name@example.com).\n\n✉️ Please provide your email address:"
            session["email"] = message
            req["mobile"] = session.get("mobile", "")
            req["email"] = session.get("email", "")
            req["additional_answers"] = session.get("additional_answers", {})
            req["deep_answers"] = session.get("deep_answers", {})
            session["requirements"] = req
            session["step"] = "confirm"

            # ----- ITEMIZED PROPOSAL -----
            price, timeline = calculate_price_and_timeline(req)
            extra_services = get_extra_services()
            extra_features_list = req.get("extra_features", [])

            items = []

            if req.get("domain"):
                items.append("• Domain Registration: PKR 5,000")

            pages = req.get("pages", 5)
            if pages > 5:
                extra_pages = pages - 5
                extra_cost = extra_pages * 5000
                items.append(f"• {extra_pages} extra page(s): +PKR {extra_cost:,}")

            if req.get("ecommerce"):
                items.append("• E‑commerce Functionality: PKR 50,000")

            if req.get("chatbot"):
                items.append("• AI Chatbot: PKR 30,000")

            if req.get("seo"):
                items.append("• SEO Optimization: PKR 25,000")

            for feat_key in extra_features_list:
                if feat_key in extra_services:
                    svc = extra_services[feat_key]
                    items.append(f"• {svc['name'].title()}: +PKR {svc['price']:,} (timeline +{svc['timeline']} days)")

            if req.get("inventory", "").lower() == "yes":
                items.append("• Inventory Management: +PKR 30,000 (+5 days)")

            if req.get("data", "").lower() == "yes":
                items.append("• Database Integration: +PKR 40,000 (+8 days)")

            itemized_text = "\n".join(items) if items else "• No services selected"

            # Additional info
            add_answers = session.get("additional_answers", {})
            add_text = ""
            if any(add_answers.values()):
                add_text = "\n\n📌 **Additional Info:**\n"
                if add_answers.get("purpose"):
                    add_text += f"• Purpose: {add_answers['purpose']}\n"
                if add_answers.get("theme"):
                    add_text += f"• Theme: {add_answers['theme']}\n"
                if add_answers.get("content"):
                    add_text += f"• Content: {add_answers['content']}\n"
                if add_answers.get("inventory"):
                    add_text += f"• Inventory Management: {add_answers['inventory']}\n"
                if add_answers.get("data"):
                    add_text += f"• Database Integration: {add_answers['data']}\n"

            deep_answers = session.get("deep_answers", {})
            deep_text = ""
            if deep_answers:
                deep_text = "\n\n📌 **Deep Dive Responses:**\n"
                for key, val in deep_answers.items():
                    deep_text += f"• {key}: {val}\n"

            media_text = ""
            if req.get("media_text"):
                media_text += f"\n\n📝 **Client Notes:** {req['media_text']}\n"
            if req.get("media_image"):
                media_text += f"\n🖼️ **Image uploaded** (view in admin panel)\n"

            contact_text = f"\n\n📞 **Contact Details:**\n• Mobile: {req.get('mobile', '')}\n• Email: {req.get('email', '')}"

            return f"""📋 **Your Project Proposal**

**Selected Services (itemized):**
{itemized_text}

💰 **Total Cost:** PKR {price:,}
⏱️ **Total Timeline:** {timeline} working days
{add_text}{deep_text}{media_text}{contact_text}

❓ **Agree?** (Reply: **Confirm** or **Cancel**)

⚠️ *To add more extras, type 'add more'*"""

    elif step == "confirm":
        if "confirm" in msg_lower or "agree" in msg_lower:
            project_id, price, timeline = create_project(session_id, req)
            del user_sessions[session_id]
            return f"""✅ **Project Confirmed!**

**Project ID:** `{project_id}`
**Total Cost:** PKR {price:,}
**Timeline:** {timeline} days

Use `status {project_id}` anytime.
We'll contact you within 24 hours. 🚀"""
        elif "cancel" in msg_lower:
            del user_sessions[session_id]
            return "❌ Cancelled. Start again with 'I want to build a website'.\n📞 For special requests, contact admin: +92 300 1234567"
        elif "add more" in msg_lower:
            session["step"] = "asking_extra"
            extra_services = get_extra_services()
            extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
            return f"✨ **Add more extras**\n\nAvailable:\n{extra_list}\n\nType name or **done**."
        else:
            return "Please reply **Confirm**, **Cancel**, or **add more**."

    return None

# ---------- Media upload endpoint ----------
@app.route('/api/upload_media', methods=['POST'])
def upload_media():
    data = request.json
    session_id = data.get('session_id')
    media_text = data.get('text', '')
    image_base64 = data.get('image', '')
    if session_id in user_sessions:
        session = user_sessions[session_id]
        if session.get("waiting_for_media"):
            if media_text:
                session["media_text"] = media_text
            if image_base64:
                session["media_image"] = image_base64
            return jsonify({"status": "ok", "message": "Media saved"})
    return jsonify({"status": "error", "message": "Session not in media upload mode"}), 400

# ---------- Package details ----------
def package_details(query):
    q = query.lower()
    if "basic" in q:
        return "**Basic Website** – PKR 50,000 (7-10 days)\n✅ 5 pages, responsive, basic SEO, contact form, social links."
    if "standard" in q:
        return "**Standard Website** – PKR 1,20,000 (15-20 days)\n✅ 10 pages, CMS, advanced SEO, blog, chatbot, 1 month support."
    if "premium" in q:
        return "**Premium Website** – PKR 2,50,000 (25-30 days)\n✅ Unlimited pages, e‑commerce, payment gateway, user accounts, custom animations, 6 months support."
    return None

# ---------- Main response handler ----------
def get_final_response(user_message, session_id):
    step_resp = process_step_by_step(session_id, user_message)
    if step_resp:
        return step_resp

    status_match = re.search(r'status\s+([A-Z0-9\-]+)', user_message.lower())
    if status_match:
        pid = status_match.group(1).upper()
        proj = get_project(pid)
        if proj:
            status = proj.get("status", "pending")
            emoji = {"pending":"⏳", "in-progress":"🔄", "completed":"✅", "declined":"❌"}.get(status, "❓")
            msg = proj.get("admin_message", "")
            extra = f"\n📝 **Admin note:** {msg}" if msg else ""
            req = proj.get("requirements", {})
            media_info = ""
            if req.get("media_text"):
                media_info += f"\n📝 **Client Notes:** {req['media_text']}"
            if req.get("media_image"):
                media_info += "\n🖼️ **Image uploaded** (view in admin panel)"
            return f"📦 **Project {pid}**\nStatus: {emoji} {status.upper()}{extra}{media_info}\nTotal: PKR {proj.get('calculated_price',0):,}\nTimeline: {proj.get('calculated_timeline',0)} days"
        else:
            return f"❌ Project ID `{pid}` not found."

    pkg = package_details(user_message)
    if pkg:
        return pkg

    return "- How can I help? Services: website design, e‑commerce, SEO, chatbots.\n- **To start a project, say 'I want to build a website'**"

# ---------- API Routes ----------
@app.route('/api/chat', methods=['POST'])
def chat():
    data = request.json
    message = data.get('message', '')
    session_id = data.get('session_id', str(uuid.uuid4()))
    if not message:
        return jsonify({"reply": "Please say something."})
    store_ip_for_session(session_id)
    reply = get_final_response(message, session_id)
    save_message(session_id, "user", message)
    save_message(session_id, "assistant", reply)
    return jsonify({"reply": reply, "session_id": session_id})

@app.route('/api/history', methods=['GET'])
def history():
    session_id = request.args.get('session_id')
    if not session_id:
        return jsonify({"error": "Missing session_id"}), 400
    messages = get_chat_history(session_id)
    return jsonify({"messages": messages})

@app.route('/api/get_ip', methods=['GET'])
def get_ip():
    session_id = request.args.get('session_id')
    if session_id:
        store_ip_for_session(session_id)
    return jsonify({"ip": get_client_ip()})

@app.route('/api/projects', methods=['GET'])
def get_projects():
    snap = ref.child("projects").get()
    return jsonify({"projects": list(snap.values()) if snap else []})

@app.route('/api/project/<project_id>/status', methods=['PUT'])
def update_status(project_id):
    data = request.json
    status = data.get('status')
    if status not in ['pending', 'in-progress', 'completed', 'declined']:
        return jsonify({"error": "Invalid status"}), 400
    update_project_status(project_id, status)
    return jsonify({"message": "Status updated"})

@app.route('/api/project/<project_id>/message', methods=['PUT'])
def update_message(project_id):
    data = request.json
    msg = data.get('message', '')
    update_project_message(project_id, msg)
    return jsonify({"message": "Message updated"})

@app.route('/api/services', methods=['GET'])
def get_services():
    services = get_extra_services()
    return jsonify({"services": services})

@app.route('/api/services', methods=['POST'])
def add_service():
    data = request.json
    key = data.get('key')
    name = data.get('name')
    price = int(data.get('price', 0))
    timeline = int(data.get('timeline', 0))
    if not key or not name:
        return jsonify({"error": "Missing key or name"}), 400
    service = {
        "name": name,
        "price": price,
        "timeline": timeline,
        "display": f"{name} (+PKR {price:,}, +{timeline} days)"
    }
    ref.child(f"extra_services/{key}").set(service)
    return jsonify({"message": "Service added"})

@app.route('/api/services/<key>', methods=['PUT'])
def update_service(key):
    data = request.json
    name = data.get('name')
    price = int(data.get('price', 0))
    timeline = int(data.get('timeline', 0))
    if not name:
        return jsonify({"error": "Missing name"}), 400
    service = {
        "name": name,
        "price": price,
        "timeline": timeline,
        "display": f"{name} (+PKR {price:,}, +{timeline} days)"
    }
    ref.child(f"extra_services/{key}").update(service)
    return jsonify({"message": "Service updated"})

@app.route('/api/services/<key>', methods=['DELETE'])
def delete_service(key):
    ref.child(f"extra_services/{key}").delete()
    return jsonify({"message": "Service deleted"})

@app.route('/api/delete_all_projects', methods=['DELETE'])
def delete_all_projects():
    confirm = request.args.get('confirm')
    if confirm != 'YES':
        return jsonify({"error": "Must provide ?confirm=YES"}), 400
    ref.child("projects").delete()
    return jsonify({"message": "All projects deleted"})

# ---------- Admin route (serves admin.html) ----------
@app.route('/admin')
def admin():
    return send_from_directory('.', 'admin.html')

@app.route('/')
def index():
    return send_from_directory('.', 'index.html')

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 7860))
    app.run(host='0.0.0.0', port=port)