File size: 35,892 Bytes
8efccc5
d1d7ef1
ac4bf94
 
 
 
4fc9006
8f2bfe4
 
ac4bf94
 
4fc9006
ac4bf94
bf53294
d1d7ef1
4fc9006
44c67f8
bf53294
8efccc5
d1d7ef1
 
 
bf53294
b02d0dd
bf53294
 
 
8efccc5
b02d0dd
bf53294
8f2bfe4
 
 
 
 
 
 
 
 
 
 
bf53294
 
b02d0dd
bf53294
 
 
 
 
 
4fc9006
bf53294
 
 
 
d1d7ef1
8e5fe2a
bf53294
8efccc5
 
d1d7ef1
8efccc5
 
d1d7ef1
8efccc5
8e5fe2a
8efccc5
 
 
ac4bf94
8efccc5
ac4bf94
613ff6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac4bf94
8e5fe2a
d727447
8e5fe2a
ac4bf94
8e5fe2a
 
4fc9006
d1d7ef1
 
8e5fe2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b81f6ed
8e5fe2a
 
ce4522d
ccbdf08
8e5fe2a
 
 
ce4522d
 
ccbdf08
8e5fe2a
ccbdf08
f2e6770
613ff6c
f2e6770
ce4522d
613ff6c
 
8e5fe2a
 
8efccc5
ac4bf94
8e5fe2a
8efccc5
b81f6ed
8efccc5
bf53294
b81f6ed
8efccc5
8e5fe2a
f2e6770
 
8e5fe2a
 
bf53294
f2e6770
8efccc5
 
 
 
b81f6ed
8e5fe2a
 
 
 
613ff6c
b81f6ed
8e5fe2a
b81f6ed
ccbdf08
8e5fe2a
 
f2e6770
b81f6ed
8efccc5
bf53294
8e5fe2a
 
 
 
 
 
ac4bf94
8efccc5
8e5fe2a
 
e3e2438
b81f6ed
8e5fe2a
f2e6770
8e5fe2a
f2e6770
8e5fe2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8efccc5
ac4bf94
d1d7ef1
 
 
8e5fe2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d727447
 
8e5fe2a
 
 
 
bf53294
 
d727447
8e5fe2a
 
ac4bf94
8efccc5
 
d727447
68eb1bc
d727447
 
 
 
 
8efccc5
 
d1d7ef1
 
4fc9006
d1d7ef1
4fc9006
 
d1d7ef1
 
 
4fc9006
 
d1d7ef1
 
 
 
68eb1bc
 
 
 
 
 
 
 
 
 
 
 
 
4fc9006
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68eb1bc
d1d7ef1
4fc9006
 
68eb1bc
4fc9006
 
 
 
 
 
 
 
 
 
d1d7ef1
 
 
 
 
 
 
 
 
 
 
 
4fc9006
 
 
 
d1d7ef1
8efccc5
ac4bf94
 
 
d1d7ef1
 
ac4bf94
8efccc5
bf53294
ac4bf94
 
d1d7ef1
bf53294
ac4bf94
 
d727447
bf53294
ac4bf94
 
d1d7ef1
ac4bf94
d727447
68eb1bc
ac4bf94
 
d1d7ef1
8e5fe2a
d727447
bf53294
8e5fe2a
 
 
 
 
d727447
8e5fe2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68eb1bc
 
bf53294
 
ac4bf94
d1d7ef1
d727447
d1d7ef1
4fc9006
 
 
 
 
 
 
 
 
 
 
 
d1d7ef1
 
 
4fc9006
d1d7ef1
4fc9006
d727447
d1d7ef1
 
 
 
 
d76c880
 
d727447
d1d7ef1
d727447
d1d7ef1
d727447
 
bf53294
 
 
ac4bf94
 
 
bf53294
d1d7ef1
bf53294
ac4bf94
bf53294
 
ac4bf94
bf53294
 
ac4bf94
8e5fe2a
ac4bf94
 
d1d7ef1
d727447
8e5fe2a
 
 
 
 
d727447
fe8f606
 
 
 
 
d1d7ef1
bf53294
 
 
d1d7ef1
 
bf53294
 
d1d7ef1
bf53294
d1d7ef1
 
bf53294
 
27a87bc
8efccc5
ac4bf94
8e5fe2a
ccbdf08
8efccc5
d1d7ef1
4fc9006
d1d7ef1
4fc9006
 
d1d7ef1
 
 
8efccc5
 
d1d7ef1
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
import gradio as gr
from google_play_scraper import search, app as play_app
import os
import time
from datetime import datetime
import json
import requests

from huggingface_hub import HfApi, hf_hub_download, create_repo

# -----------------------------
# CONFIG & API CONNECTION
# -----------------------------
HF_TOKEN = os.getenv("HF_TOKEN")
APP_PASSWORD = os.getenv("APP_PASSWORD") 
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") # Ensure this is set in HF Space Secrets
DATASET_REPO = "kacapower/lexical-space-data"
THEME_FILE_NAME = "website_theme.xml"

# -----------------------------
# CORE FUNCTIONS
# -----------------------------
def save_theme_to_dataset(xml_file):
    """Saves the uploaded XML file directly to the private hf dataset."""
    if xml_file is None:
        return "❌ Please upload an XML file first."
        
    try:
        file_path = xml_file if isinstance(xml_file, str) else xml_file.name
        
        try:
            create_repo(
                repo_id=DATASET_REPO, 
                repo_type="dataset", 
                private=True, 
                exist_ok=True, 
                token=HF_TOKEN
            )
        except Exception as repo_err:
            return f"❌ Failed to access or create repository: {repo_err}. Check your HF_TOKEN permissions."

        api = HfApi()
        api.upload_file(
            path_or_fileobj=file_path,
            path_in_repo=THEME_FILE_NAME,
            repo_id=DATASET_REPO,
            repo_type="dataset",
            token=HF_TOKEN,
            commit_message="Updated website theme XML"
        )
        return "✅ Theme successfully pushed to your private dataset! The AI will now use this for styling."
        
    except Exception as e:
        return f"❌ Error saving theme to dataset: {e}"


def generate_blogger_html(app_query, custom_link, mirror_1, mirror_2, mod_features, theme_color, telegram_link, custom_size, custom_date, req_name, req_link, tutorial_link, root_req, arch_input, lexical_score, pros_input, cons_input, vt_link, related_name, related_link, coffee_link):
    try:
        search_results = search(app_query, lang='en', country='us')
        if not search_results:
            return "Error: Could not find this app on the Play Store.", "<b>App not found</b>", "0", "0"
            
        app_id = search_results[0]['appId']
        app_details = play_app(app_id, lang='en', country='us')
        
        # Base Extractions
        title = app_details.get('title', app_query)
        icon_url = app_details.get('icon', '')
        rating = round(app_details.get('score', 4.5), 1)
        reviews_count = app_details.get('ratings', 1000)
        category = app_details.get('genre', 'Utility')
        developer = app_details.get('developer', 'Unknown Developer')
        # --- INSTALL FORMATTER (10,000,000,000+ to 10B+) ---
        raw_installs = app_details.get('installs', '10,000+')
        clean_num = raw_installs.replace(',', '').replace('+', '')
        if clean_num.isdigit():
            num = int(clean_num)
            if num >= 1_000_000_000:
                installs = f"{num // 1_000_000_000}B+"
            elif num >= 1_000_000:
                installs = f"{num // 1_000_000}M+"
            elif num >= 1_000:
                installs = f"{num // 1_000}K+"
            else:
                installs = f"{num}+"
        else:
            installs = raw_installs
        # ---------------------------------------------------
        version = app_details.get('version', 'Varies with device')
        recent_changes = app_details.get('recentChanges', '')
        
        final_size = custom_size.strip() if custom_size else app_details.get('size', 'Varies')
        updated_ts = app_details.get('updated', 0)
        final_date = custom_date.strip() if custom_date else (datetime.fromtimestamp(updated_ts).strftime('%B %d, %Y') if updated_ts else "Recently")
        full_description = app_details.get('descriptionHTML', app_details.get('summary', 'Premium app.'))
        screenshots = app_details.get('screenshots', [])[:4] 
        video_url = app_details.get('video', None)

        # 1. Mod Features
        features_list = "".join([f'<li style="margin-bottom: 10px;"><i class="fa-solid fa-check" style="color: {theme_color}; margin-right: 12px; font-size: 1.1rem;"></i> {f.strip()}</li>\n' for f in mod_features.split(',') if f.strip()])

        # 2. Pros & Cons
        pros_html = "".join([f'<li style="margin-bottom: 6px;"><i class="fa-solid fa-plus" style="color: #10b981; margin-right: 8px;"></i> {p.strip()}</li>' for p in pros_input.split(',') if p.strip()])
        cons_html = "".join([f'<li style="margin-bottom: 6px;"><i class="fa-solid fa-minus" style="color: #ef4444; margin-right: 8px;"></i> {c.strip()}</li>' for c in cons_input.split(',') if c.strip()])

        # 3. Dynamic Links (Mirrors, VT, Coffee)
        mirror1_html = f'<a href="{mirror_1.strip()}" target="_blank" style="flex: 1; min-width: 150px; background: rgba(255,255,255,0.1); color: #fff; text-decoration: none; padding: 12px 15px; border-radius: 50px; font-weight: 700; border: 1px solid rgba(255,255,255,0.2);"><i class="fa-solid fa-server"></i> Mirror 1</a>' if mirror_1 else ""
        mirror2_html = f'<a href="{mirror_2.strip()}" target="_blank" style="flex: 1; min-width: 150px; background: rgba(255,255,255,0.1); color: #fff; text-decoration: none; padding: 12px 15px; border-radius: 50px; font-weight: 700; border: 1px solid rgba(255,255,255,0.2);"><i class="fa-solid fa-server"></i> Mirror 2</a>' if mirror_2 else ""
        vt_html = f'<p style="font-size: 0.85rem; color: #10b981; margin-top: 15px;"><a href="{vt_link.strip()}" target="_blank" style="color: #10b981; text-decoration: none;"><i class="fa-solid fa-shield-check"></i> 100% Safe - Verified by VirusTotal Scan</a></p>' if vt_link else '<p style="font-size: 0.85rem; color: #64748b; margin-top: 15px;"><i class="fa-solid fa-shield-halved"></i> Links encrypted. Checked for safety.</p>'
        coffee_html = f'<a href="{coffee_link.strip()}" target="_blank" style="display: inline-block; background: #ffdd00; color: #000; padding: 8px 20px; border-radius: 25px; text-decoration: none; font-weight: bold; font-size: 0.95rem; transition: 0.2s;">☕ Buy Me a Coffee</a>' if coffee_link else ""

        # 4. Optional Blocks (Changelog, Companion, Related)
        changelog_block = f'<h2 style="border-left: 5px solid {theme_color}; padding-left: 12px; margin-bottom: 15px; font-size: 1.4rem;">What\'s New</h2><div style="background: rgba(0,0,0,0.3); border: 1px solid rgba(255,255,255,0.05); padding: 15px; border-radius: 12px; font-family: monospace; color: #10b981; margin-bottom: 35px; white-space: pre-wrap; font-size: 0.9rem;">{recent_changes}</div>' if recent_changes else ""
        
        related_html = f'<div style="border: 1px dashed {theme_color}; padding: 25px; border-radius: 16px; text-align: center; margin-bottom: 35px;"><h3 style="margin-top:0; color:#fff;">Looking for more?</h3><a href="{related_link.strip()}" style="color: {theme_color}; font-weight: 800; font-size: 1.1rem; text-decoration: none;">Download {related_name.strip()} Mod APK <i class="fa-solid fa-arrow-right"></i></a></div>' if related_name and related_link else ""

        req_app_html = f'<h2 style="border-left: 5px solid #ef4444; padding-left: 12px; margin-bottom: 20px; font-size: 1.4rem;">Requirements</h2><div style="background: rgba(239, 68, 68, 0.05); border: 1px solid rgba(239, 68, 68, 0.2); padding: 20px; border-radius: 16px; display: flex; align-items: center; gap: 15px; margin-bottom: 35px;"><div style="width: 50px; height: 50px; background: rgba(239, 68, 68, 0.1); border-radius: 12px; display: flex; align-items: center; justify-content: center; color: #ef4444; font-size: 1.5rem;"><i class="fa-solid fa-puzzle-piece"></i></div><div style="flex: 1;"><h3 style="margin: 0 0 5px 0; font-size: 1.1rem;">{req_name}</h3><p style="margin: 0; font-size: 0.85rem; color: #94a3b8;">Companion app required.</p></div><a href="{req_link}" target="_blank" rel="nofollow noopener" style="background: #ef4444; color: #fff; padding: 10px 20px; border-radius: 50px; text-decoration: none; font-weight: 700; font-size: 0.9rem; transition: 0.3s; white-space: nowrap; box-shadow: 0 5px 15px rgba(239, 68, 68, 0.3);">Get Companion <i class="fa-solid fa-download" style="margin-left: 5px;"></i></a></div>' if req_name and req_link else ""
        
        tutorial_btn = f'<a href="{tutorial_link.strip()}" target="_blank" style="color: #a855f7; text-decoration: none; transition: 0.2s;"><i class="fa-solid fa-book-open"></i> View Tutorial</a>' if tutorial_link else ""

        # Media Blocks
        screenshots_html = f'<h2 style="border-left: 5px solid {theme_color}; padding-left: 12px; margin-top: 35px; font-size: 1.4rem;">App Screenshots</h2><div style="display: flex; gap: 15px; overflow-x: auto; padding-bottom: 15px; scroll-snap-type: x mandatory; margin-bottom: 35px;">' + "".join([f'<img src="{s}" style="height: 300px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.1); scroll-snap-align: start; box-shadow: 0 5px 15px rgba(0,0,0,0.3);">' for s in screenshots]) + '</div>' if screenshots else ""
        video_html = f'<h2 style="border-left: 5px solid {theme_color}; padding-left: 12px; margin-top: 35px; font-size: 1.4rem;">Official Trailer</h2><div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; border-radius: 16px; box-shadow: 0 10px 25px rgba(0,0,0,0.4); margin-bottom: 35px;"><iframe src="{video_url.replace("watch?v=", "embed/")}" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" frameborder="0" allowfullscreen></iframe></div>' if video_url else ""

        root_color = "#10b981" if "No" in root_req else "#ef4444"

        
        # Schemas
        schema_app = {"@context": "https://schema.org", "@type": "SoftwareApplication", "name": title, "operatingSystem": "ANDROID", "applicationCategory": category, "image": icon_url, "author": { "@type": "Organization", "name": developer }, "aggregateRating": {"@type": "AggregateRating", "ratingValue": str(rating), "ratingCount": str(reviews_count)}, "offers": { "@type": "Offer", "price": "0.00", "priceCurrency": "USD" }}
        schema_faq = {"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": f"Is {title} Mod safe?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, verified by Lexical Space."}}, {"@type": "Question", "name": f"Does {title} require root access?", "acceptedAnswer": {"@type": "Answer", "text": "No, it works on any non-rooted Android device."}}]}
        schema_sysreq = {"@context": "https://schema.org", "@type": "SoftwareApplication", "name": title, "operatingSystem": "ANDROID", "applicationCategory": category, "author": { "@type": "Organization", "name": developer }, "requirements": { "@type": "SoftwareApplicationRequirements", "name": "Minimum System Requirements", "operatingSystem": "Android 9.0 (Pie)+", "ram": "4 GB+", "storage": "100 MB+" }}
        schema_script = f'<script type="application/ld+json">\n[{json.dumps(schema_app)}, {json.dumps(schema_faq)}, {json.dumps(schema_sysreq)}]\n</script>'

        # THE FINAL HTML
        html_template = f"""
{schema_script}
<div style="display: none;"><img src="{icon_url}" alt="Download {title} Mod APK" /></div>

<div class="app-post-wrapper" style="background: #0f172a; width: 100%; min-height: 100vh; margin: 0; padding: 40px 5%; box-sizing: border-box; color: #fff; font-family: 'Plus Jakarta Sans', sans-serif;">
  
  <div style="display: flex; gap: 20px; align-items: center; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 25px; margin-bottom: 25px; flex-wrap: wrap;">
     <img src="{icon_url}" alt="{title} Premium" style="width: 110px; height: 110px; border-radius: 28px; box-shadow: 0 10px 20px rgba(0,0,0,0.5); flex-shrink: 0;">
     <div style="flex: 1; min-width: 250px;">
        <h1 style="margin: 0 0 10px 0; font-size: 2.3rem; font-weight: 800; line-height: 1.1;">{title} <span style="font-size: 0.85rem; background: {theme_color}; padding: 5px 12px; border-radius: 12px; vertical-align: middle; margin-left: 10px;">MOD</span></h1>
        <p style="margin: 0 0 15px 0; color: #94a3b8; font-weight: 600; font-size: 1.05rem;"><i class="fa-solid fa-layer-group"></i> {category} • Max Store Verified</p>
        <div style="display: flex; flex-wrap: wrap; gap: 20px; font-size: 0.95rem; color: #cbd5e1; font-weight: 700;">
            <span><i class="fa-solid fa-star" style="color:#f59e0b;"></i> {rating} (Play Store)</span>
            <span><i class="fa-solid fa-award" style="color:#a855f7;"></i> {lexical_score}/10 (Lexical Score)</span>
            <span><i class="fa-solid fa-download" style="color: #38bdf8;"></i> {installs}</span>
            <span><i class="fa-brands fa-android" style="color: #10b981;"></i> Android 9.0+</span>
        </div>
     </div>
  </div>

  <div style="text-align: center; margin-bottom: 35px; background: #020617; padding: 30px 15px; border-radius: 20px; border: 1px solid rgba(255,255,255,0.03);">
     <div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 15px;">
         <a href="{custom_link}" target="_blank" rel="nofollow noopener" style="flex: 2; min-width: 260px; max-width: 400px; background: {theme_color}; color: #fff; text-decoration: none; padding: 14px 20px; border-radius: 50px; font-weight: 800; font-size: 1.1rem; box-shadow: 0 0 25px {theme_color}80; transition: transform 0.3s ease;"><i class="fa-solid fa-cloud-arrow-down"></i> Download APK</a>
         {mirror1_html}
         {mirror2_html}
         <a href="https://play.google.com/store/apps/details?id={app_id}" target="_blank" rel="nofollow noopener" style="flex: 2; min-width: 260px; max-width: 400px; background: #10b981; color: #fff; text-decoration: none; padding: 14px 20px; border-radius: 50px; font-weight: 800; font-size: 1.1rem; box-shadow: 0 0 25px rgba(16, 185, 129, 0.4); transition: transform 0.3s ease;"><i class="fa-brands fa-google-play"></i> Play Store</a>
     </div>
     {vt_html}
     
     <div style="display: flex; justify-content: center; flex-wrap: wrap; gap: 20px; margin-top: 20px; font-size: 0.9rem; font-weight: 600;">
         {tutorial_btn}
         <a href="mailto:admin@lexicalspace.com?subject=Broken Link Report: {title}" style="color: #ef4444; text-decoration: none;"><i class="fa-solid fa-link-slash"></i> Link not working?</a>
         <a href="mailto:admin@lexicalspace.com?subject=App Issue Report: {title}" style="color: #f59e0b; text-decoration: none; transition: 0.2s;"><i class="fa-solid fa-flag"></i> Report Issue</a>
     </div>
  </div>
  
  <div style="background: rgba(56, 189, 248, 0.05); border: 1px solid rgba(56, 189, 248, 0.2); padding: 20px; border-radius: 16px; text-align: center; margin-bottom: 35px; display: flex; flex-direction: column; align-items: center;">
    <strong style="color: #e2e8f0; font-size: 1.05rem; margin-bottom: 12px;">Support Lexical Space:</strong>
    <div style="display: flex; gap: 15px; flex-wrap: wrap; justify-content: center;">
        <a href="{telegram_link}" target="_blank" style="background: #0088cc; color: white; padding: 8px 20px; border-radius: 25px; text-decoration: none; font-weight: bold; font-size: 0.95rem;">✈️ Join Telegram</a>
        {coffee_html}
    </div>
  </div>

  {req_app_html}
  {changelog_block}

  <h2 style="border-left: 5px solid #38bdf8; padding-left: 12px; margin-bottom: 20px; font-size: 1.4rem;">App Information</h2>
  <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 15px; margin-bottom: 35px; background: rgba(255,255,255,0.02); padding: 20px; border-radius: 16px; border: 1px solid rgba(255,255,255,0.05);">
      <div style="background: rgba(255,255,255,0.03); padding: 15px; border-radius: 10px;"><span style="display: block; font-size: 0.75rem; color: #94a3b8; text-transform: uppercase;">Developer</span><strong style="font-size: 1rem;">{developer}</strong></div>
      <div style="background: rgba(255,255,255,0.03); padding: 15px; border-radius: 10px;"><span style="display: block; font-size: 0.75rem; color: #94a3b8; text-transform: uppercase;">Version</span><strong style="font-size: 1rem;">{version}</strong></div>
      <div style="background: rgba(255,255,255,0.03); padding: 15px; border-radius: 10px;"><span style="display: block; font-size: 0.75rem; color: #94a3b8; text-transform: uppercase;">Updated</span><strong style="font-size: 1rem;">{final_date}</strong></div>
      <div style="background: rgba(255,255,255,0.03); padding: 15px; border-radius: 10px;"><span style="display: block; font-size: 0.75rem; color: #94a3b8; text-transform: uppercase;">File Size</span><strong style="font-size: 1rem;">{final_size}</strong></div>
      <div style="background: rgba(255,255,255,0.03); padding: 15px; border-radius: 10px;"><span style="display: block; font-size: 0.75rem; color: #94a3b8; text-transform: uppercase;">Architecture</span><strong style="font-size: 1rem;">{arch_input}</strong></div>
      <div style="background: rgba(255,255,255,0.03); padding: 15px; border-radius: 10px;"><span style="display: block; font-size: 0.75rem; color: #94a3b8; text-transform: uppercase;">Root Access</span><strong style="font-size: 1rem; color: {root_color};">{root_req}</strong></div>
  </div>

  <h2 style="border-left: 5px solid {theme_color}; padding-left: 12px; margin-bottom: 20px; font-size: 1.4rem;">Mod Features</h2>
  <div style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.2); padding: 25px; border-radius: 16px; margin-bottom: 35px;">
      <ul style="color: #f1f5f9; line-height: 2; list-style-type: none; padding-left: 0; margin: 0; font-weight: 700;">{features_list}</ul>
  </div>

  <h2 style="border-left: 5px solid {theme_color}; padding-left: 12px; margin-bottom: 20px; font-size: 1.4rem;">Pros & Cons</h2>
  <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 35px;">
      <div style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.2); padding: 20px; border-radius: 16px;">
          <h3 style="color: #10b981; margin-top: 0; margin-bottom: 15px;"><i class="fa-solid fa-thumbs-up"></i> Pros</h3>
          <ul style="list-style: none; padding: 0; margin: 0; color: #cbd5e1; line-height: 1.8;">{pros_html}</ul>
      </div>
      <div style="background: rgba(239, 68, 68, 0.05); border: 1px solid rgba(239, 68, 68, 0.2); padding: 20px; border-radius: 16px;">
          <h3 style="color: #ef4444; margin-top: 0; margin-bottom: 15px;"><i class="fa-solid fa-thumbs-down"></i> Cons</h3>
          <ul style="list-style: none; padding: 0; margin: 0; color: #cbd5e1; line-height: 1.8;">{cons_html}</ul>
      </div>
  </div>

  {video_html}
  {screenshots_html}

  <h2 style="border-left: 5px solid #f59e0b; padding-left: 12px; margin-bottom: 20px; font-size: 1.4rem;">Installation Guide</h2>
  <div style="background: rgba(255,255,255,0.02); padding: 25px; border-radius: 16px; margin-bottom: 35px;">
      <ol style="color: #cbd5e1; line-height: 1.8; margin: 0; padding-left: 20px;">
          <li style="margin-bottom: 10px;">Download the <strong>{title} Mod APK</strong> file from the secure link above.</li>
          <li style="margin-bottom: 10px;">Go to your device <strong>Settings > Security</strong> and enable "Unknown Sources".</li>
          <li style="margin-bottom: 10px;">Open your File Manager, locate the downloaded APK, and install it.</li>
          <li>Launch the app and enjoy all premium features!</li>
      </ol>
  </div>

  <h2 style="border-left: 5px solid #a855f7; padding-left: 12px; margin-bottom: 20px; font-size: 1.4rem;">Frequently Asked Questions</h2>
  <div style="margin-bottom: 40px;">
      <details style="background: rgba(255,255,255,0.03); padding: 15px 20px; border-radius: 12px; margin-bottom: 10px; cursor: pointer; border: 1px solid rgba(255,255,255,0.05);">
          <summary style="font-weight: 700; color: #fff;">Is {title} Mod safe to use?</summary>
          <p style="margin-top: 15px; margin-bottom: 0; color: #cbd5e1; line-height: 1.6;">Yes! All files on Lexical Space are strictly tested and verified. Always download directly from our site to ensure device security.</p>
      </details>
      <details style="background: rgba(255,255,255,0.03); padding: 15px 20px; border-radius: 12px; margin-bottom: 10px; cursor: pointer; border: 1px solid rgba(255,255,255,0.05);">
          <summary style="font-weight: 700; color: #fff;">Do I need to root my device?</summary>
          <p style="margin-top: 15px; margin-bottom: 0; color: #cbd5e1; line-height: 1.6;">Please refer to the "Root Access" status in the App Information box above. Most of our mods do not require root.</p>
      </details>
  </div>

  {related_html}
  
  <h2 style="border-left: 5px solid #f59e0b; padding-left: 12px; margin-bottom: 20px; font-size: 1.4rem;">About Original {title}</h2>
  <div style="color: #cbd5e1; line-height: 1.8; font-size: 1rem; overflow: hidden; margin-bottom: 40px;">
    {full_description}
  </div>
  
  <div style="border-top: 1px solid rgba(255,255,255,0.1); padding-top: 20px; font-size: 0.75rem; color: #64748b; text-align: center;">
      DMCA: Lexical Space complies with 17 U.S.C. § 512 and the Digital Millennium Copyright Act.
  </div>
</div>
"""
        word_count = str(len(html_template.split()))
        keyword_density = str(html_template.lower().count(title.lower()[:10])) 
        
        with open("latest_draft.txt", "w", encoding="utf-8") as f:
            f.write(html_template)

        return html_template, html_template, word_count, keyword_density
        
    except Exception as e:
        return f"Error generating HTML: {str(e)}", f"<b>Error occurred: {str(e)}</b>", "0", "0"
# -----------------------------
# OPENROUTER AI ENHANCER (XML FETCH + CLAUDE/GPT/GEMINI)
# -----------------------------
def enhance_with_openrouter(raw_html, style_name, selected_model, state):
    """Downloads XML from Dataset, reads it, and uses OpenRouter API to exact-match the styles."""
    if not state.get("logged_in") or (time.time() - state.get("login_time", 0) > 1800):
        return "Session expired.", "Session Expired.", "0", "0", gr.update(visible=False)

    if not OPENROUTER_API_KEY:
        return raw_html, "<b>Error: OPENROUTER_API_KEY not found in HF Space secrets.</b>", "0", "0", gr.update(visible=False)
        
    if not raw_html or raw_html.startswith("Error"):
        return raw_html, "<b>Please generate Base HTML first before enhancing.</b>", "0", "0", gr.update(visible=False)

    # 1. Fetch the exact XML file from Hugging Face Dataset
    xml_content = ""
    try:
        downloaded_theme_path = hf_hub_download(
            repo_id=DATASET_REPO, 
            filename=THEME_FILE_NAME, 
            repo_type="dataset", 
            token=HF_TOKEN
        )
        with open(downloaded_theme_path, "r", encoding="utf-8") as f:
            xml_content = f.read()
    except Exception as e:
        print(f"Failed to fetch XML: {e}")
        xml_content = "WARNING: Could not fetch website_theme.xml from dataset. Please apply generic high-quality CSS styling based on the requested style name."

    # 2. Configure OpenRouter Request
    prompt = f"""
I am providing you with the raw source code of my website's theme XML. It contains the exact CSS definitions, classes, ID's, CSS variables (like colors, fonts), and HTML structures used for the site.

<WEBSITE_THEME_XML>
{xml_content}
</WEBSITE_THEME_XML>

TASK:
I want you to re-format and re-style the following Base HTML App Post to match the style known as: '{style_name}'.
Look through the <WEBSITE_THEME_XML> provided above. Find the CSS classes, inline styles, or component structures that correspond to '{style_name}'. Apply those exact classes, color hexes, and layout structures to the Base HTML. DO NOT invent styles—extract them from the XML.

STRICT RULES:
1. CRITICAL: DO NOT remove or alter the `<script type="application/ld+json">` blocks. They are critical for SEO.
2. CRITICAL: DO NOT alter ANY `href="..."` or `src="..."` attributes. The download links, Telegram links, image links, and video iframes MUST remain exactly as they are.
3. DO NOT hallucinate or change the factual data (file size, version, rating, text content).

Base HTML Code to Enhance:
{raw_html}
    """

    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "HTTP-Referer": "https://huggingface.co/spaces/kacapower/lexical-space", 
        "X-Title": "Lexical Space Post Generator",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": selected_model,
        "messages": [
            {
                "role": "system", 
                "content": "You are the lead front-end developer. You must output ONLY raw, strictly valid HTML code. Do not wrap your response in markdown formatting like ```html. Do not include any conversational text before or after the code. Return nothing but HTML."
            },
            {
                "role": "user", 
                "content": prompt
            }
        ]
    }

    try:
        response = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload)
        response.raise_for_status() # Raise exception for bad status codes
        
        result = response.json()
        enhanced_html = result['choices'][0]['message']['content'].strip()
        
        # Strip markdown block if the model ignored the system prompt
        if enhanced_html.startswith("```html"):
            enhanced_html = enhanced_html[7:]
        if enhanced_html.endswith("```"):
            enhanced_html = enhanced_html[:-3]
            
        enhanced_html = enhanced_html.strip()
        
        # Calculate new stats
        word_count = str(len(enhanced_html.split()))
        keyword_density = "N/A (AI Enhanced)"

        # Overwrite draft with enhanced version
        with open("latest_draft.txt", "w", encoding="utf-8") as f:
            f.write(enhanced_html)

        return enhanced_html, enhanced_html, word_count, keyword_density, gr.update(value="latest_draft.txt", visible=True)

    except Exception as e:
        error_msg = str(e)
        if 'response' in locals() and response.text:
            error_msg += f" | API Response: {response.text}"
        return raw_html, f"<b>OpenRouter API Error:</b> {error_msg}<br><i>Showing unenhanced Base HTML instead.</i>", "0", "0", gr.update(visible=False)


# -----------------------------
# UI & AUTHENTICATION LOGIC
# -----------------------------
with gr.Blocks(title="Lexical Space Internal Tool", theme=gr.themes.Monochrome(primary_hue="blue")) as agent_ui:
    # State tracking
    session_state = gr.State({"logged_in": False, "login_time": 0})
    
    # --- LOGIN SCREEN ---
    with gr.Group(visible=True) as login_screen:
        gr.Markdown("# 🔒 Lexical Space Internal Tool")
        gr.Markdown("Please enter the password to unlock the Post Generator Agent. Sessions expire after 30 minutes.")
        
        with gr.Row():
            pwd_input = gr.Textbox(label="Password", type="password", scale=4)
            login_btn = gr.Button("Unlock Dashboard", variant="primary", scale=1)
            
        login_err = gr.Markdown("❌ Incorrect password.", visible=False)

    # --- MAIN APPLICATION DASHBOARD ---
    with gr.Group(visible=False) as main_app:
        gr.Markdown("# 🚀 Lexical Space V2 Post Generator")
        gr.Markdown("Search the Play Store, inject mods, and generate SEO-optimized HTML matching your XML theme.")
        
        with gr.Row():
            # --- LEFT COLUMN: SETTINGS ---
            
            with gr.Column(scale=1):
                gr.Markdown("### 1. App Parameters")
                app_input = gr.Textbox(label="App Name (e.g., TeraBox)", placeholder="Search query for Play Store...")
                link_input = gr.Textbox(label="Primary Download Link", placeholder="https://...")
                mirror_1 = gr.Textbox(label="Mirror 1 Link (Optional)", placeholder="https://...")
                mirror_2 = gr.Textbox(label="Mirror 2 Link (Optional)", placeholder="https://...")
                features_input = gr.Textbox(label="Mod Features (Comma separated)", value="Premium Unlocked, No Ads, Analytics Removed")
                
                with gr.Accordion("Requirements & Tech Specs", open=False):
                    root_req = gr.Radio(choices=["No Root Required", "Root Required"], value="No Root Required", label="Root Status")
                    arch_input = gr.Textbox(label="Architecture", value="Universal (ARM64 & ARMv7)")
                    custom_size = gr.Textbox(label="Custom File Size Override")
                    custom_date = gr.Textbox(label="Custom Updated Date Override")
                    req_app_name = gr.Textbox(label="Companion App Name (Optional)")
                    req_app_link = gr.Textbox(label="Companion App Link (Optional)")

                with gr.Accordion("Editorial, Pros & Cons", open=False):
                    lexical_score = gr.Slider(minimum=1, maximum=10, step=0.1, value=9.5, label="Lexical Mod Quality Score")
                    pros_input = gr.Textbox(label="Pros (Comma separated)", value="Fast performance, No ads, Premium unlocked")
                    cons_input = gr.Textbox(label="Cons (Comma separated)", value="Requires manual updates")
                    related_name = gr.Textbox(label="Related Mod Name (Optional)")
                    related_link = gr.Textbox(label="Related Mod Link (Optional)")

                with gr.Accordion("Trust, SEO & Links", open=False):
                    vt_link = gr.Textbox(label="VirusTotal Scan Link (Optional)")
                    tutorial_link = gr.Textbox(label="Tutorial/Guide Link (Optional)")
                    coffee_link = gr.Textbox(label="Buy Me a Coffee Link", value="https://buymeacoffee.com/lexicalspace")
                    telegram_link = gr.Textbox(label="Telegram Channel", value="https://t.me/lexicalspace") 
                    theme_color = gr.ColorPicker(label="Fallback Accent Color", value="#3b82f6")

                with gr.Accordion("Theme & XML Upload", open=False):
                    xml_theme_input = gr.File(label="Upload website_theme.xml")
                    save_theme_btn = gr.Button("Save Theme to Dataset")
                    theme_status_out = gr.Textbox(label="Theme Status", interactive=False)
                
                generate_btn = gr.Button("⚙️ Generate Base HTML", variant="primary")
                
                gr.Markdown("<hr>")
                gr.Markdown("### 2. AI Style Enhancer (OpenRouter)")
                with gr.Column():
                    or_model_dropdown = gr.Dropdown(
                        choices=[
                            "anthropic/claude-3.5-sonnet",   # Absolute best for coding/HTML
                            "google/gemini-1.5-pro",         # Huge context window
                            "openai/gpt-4o",                 # Fast and reliable
                            "meta-llama/llama-3.1-70b-instruct" # Powerful open-source
                        ],
                        label="Select AI Model",
                        value="anthropic/claude-3.5-sonnet"
                    )
                    style_dropdown = gr.Dropdown(
                        choices=["Lexical Standard", "Lexical Minimalist", "Lexical Max Store"], 
                        label="Target Post Style", 
                        value="Lexical Standard"
                    )
                    enhance_btn = gr.Button("✨ Enhance with XML Styles", variant="secondary")
                
                gr.Markdown("<hr>")
                gr.Markdown("### Post Statistics")
                with gr.Row():
                    word_count_out = gr.Textbox(label="Total Word Count", interactive=False)
                    kw_density_out = gr.Textbox(label="Keyword Mentions", interactive=False)
                
                file_download = gr.File(label="Download Draft Backup (.txt file)", visible=False, interactive=False)

            # --- RIGHT COLUMN: OUTPUT ---
            with gr.Column(scale=2):
                gr.Markdown("### 3. Output & Preview")
                with gr.Tabs():
                    with gr.Tab("Source Code (HTML)"):
                        html_output = gr.Code(label="Copy & Paste to Blogger HTML View", language="html", interactive=False)
                    with gr.Tab("Live Preview"):
                        preview_output = gr.HTML(label="How it will look on your Blog")

    # --- CONTROLLERS ---
    def verify_login(pwd, state):
        if not APP_PASSWORD:
            return state, gr.update(), gr.update(), gr.update(value="❌ APP_PASSWORD missing from Space secrets.", visible=True)
            
        if pwd == APP_PASSWORD:
            state["logged_in"] = True
            state["login_time"] = time.time()
            return state, gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
        else:
            return state, gr.update(visible=True), gr.update(visible=False), gr.update(value="❌ Incorrect password.", visible=True)

    def secure_generate(app_query, custom_link, mirror_1, mirror_2, mod_features, theme_color, telegram_link, custom_size, custom_date, req_name, req_link, tutorial_link, root_req, arch_input, lexical_score, pros_input, cons_input, vt_link, related_name, related_link, coffee_link, state):
        if not state.get("logged_in") or (time.time() - state.get("login_time", 0) > 1800):
            state["logged_in"] = False
            return ("Session expired.", "Session expired.", "0", "0", gr.update(visible=True), gr.update(visible=False), state, gr.update(visible=False))

        code, preview, words, keywords = generate_blogger_html(
            app_query, custom_link, mirror_1, mirror_2, mod_features, theme_color, telegram_link, 
            custom_size, custom_date, req_name, req_link, tutorial_link, root_req, arch_input, 
            lexical_score, pros_input, cons_input, vt_link, related_name, related_link, coffee_link
        )
        
        if os.path.exists("latest_draft.txt") and not code.startswith("Error"):
            file_update = gr.update(value="latest_draft.txt", visible=True)
        else:
            file_update = gr.update(value=None, visible=False)
            
        return (code, preview, words, keywords, gr.update(visible=False), gr.update(visible=True), state, file_update)

    # --- EVENT BINDINGS ---
    login_btn.click(
        fn=verify_login, 
        inputs=[pwd_input, session_state], 
        outputs=[session_state, login_screen, main_app, login_err]
    )
    
    save_theme_btn.click(
        fn=save_theme_to_dataset, 
        inputs=[xml_theme_input], 
        outputs=theme_status_out
    )
    
    generate_btn.click(
        fn=secure_generate,
        inputs=[app_input, link_input, mirror_1, mirror_2, features_input, theme_color, telegram_link, custom_size, custom_date, req_app_name, req_app_link, tutorial_link, root_req, arch_input, lexical_score, pros_input, cons_input, vt_link, related_name, related_link, coffee_link, session_state],
        outputs=[html_output, preview_output, word_count_out, kw_density_out, login_screen, main_app, session_state, file_download]
    )
    
    # AI OpenRouter Enhance binding
    enhance_btn.click(
        fn=enhance_with_openrouter,
        inputs=[html_output, style_dropdown, or_model_dropdown, session_state],
        outputs=[html_output, preview_output, word_count_out, kw_density_out, file_download],
        show_progress="full"
    )

if __name__ == "__main__":
    agent_ui.launch()