File size: 34,249 Bytes
d8efdc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46c28e3
d8efdc1
 
 
 
 
 
46c28e3
d8efdc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46c28e3
 
d8efdc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46c28e3
d8efdc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31f70b4
d8efdc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46c28e3
 
d8efdc1
31f70b4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
"""
APK Deep Diff Analyzer - Gradio Web Interface
Hugging Face Space Application
"""
import gradio as gr
import os
import json
import tempfile
import shutil
from typing import Optional, Tuple, List

# Add src to path
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))

from apk_analyzer import APKDeepAnalyzer
from report_generator import ReportGenerator
from utils import get_apk_info, get_file_size_formatted


# Global state for analysis results
_analysis_results = {}


def validate_apk_file(file_path: str) -> Tuple[bool, str]:
    """Validate uploaded APK file."""
    if file_path is None:
        return False, "لم يتم اختيار ملف"
    if not os.path.exists(file_path):
        return False, "الملف غير موجود"
    if not file_path.endswith('.apk'):
        return False, "الملف ليس بصيغة APK"

    import zipfile
    if not zipfile.is_zipfile(file_path):
        return False, "الملف ليس ملف ZIP/APK صالح"

    try:
        with zipfile.ZipFile(file_path, 'r') as zf:
            if "AndroidManifest.xml" not in zf.namelist():
                return False, "AndroidManifest.xml غير موجود"
            has_dex = any(name.endswith('.dex') for name in zf.namelist())
            if not has_dex:
                return False, "لا يوجد ملف DEX"
    except Exception as e:
        return False, f"خطأ في التحقق: {str(e)}"

    return True, "صالح"


def get_file_info_display(file_path: str) -> str:
    """Get formatted file info for display."""
    if file_path is None or not os.path.exists(file_path):
        return "لم يتم اختيار ملف"

    info = get_apk_info(file_path)
    return f"""
📄 **الاسم:** `{info['filename']}`
📦 **الحجم:** {info['size_formatted']} ({info['size']:,} bytes)
🔐 **SHA-256:** `{info['sha256']}`
🔑 **MD5:** `{info['md5']}`
"""


def update_file_info(file_path, is_original=True):
    """Update file info display."""
    if file_path is None:
        return ""
    info = get_file_info_display(file_path)
    return info


def run_analysis(orig_file, mod_file, progress=gr.Progress()):
    """Run deep analysis and return all results."""
    global _analysis_results

    if orig_file is None or mod_file is None:
        return [
            gr.update(visible=True, value="❌ الرجاء رفع الملفين أولاً"),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
        ]

    # Validate files
    valid_orig, msg_orig = validate_apk_file(orig_file)
    valid_mod, msg_mod = validate_apk_file(mod_file)

    if not valid_orig:
        return [
            gr.update(visible=True, value=f"❌ APK الأصلي: {msg_orig}"),
            gr.update(visible=False), gr.update(visible=False),
            gr.update(visible=False), gr.update(visible=False),
            gr.update(visible=False), gr.update(visible=False),
            gr.update(visible=False), gr.update(visible=False),
            "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        ]

    if not valid_mod:
        return [
            gr.update(visible=True, value=f"❌ APK المعدل: {msg_mod}"),
            gr.update(visible=False), gr.update(visible=False),
            gr.update(visible=False), gr.update(visible=False),
            gr.update(visible=False), gr.update(visible=False),
            gr.update(visible=False), gr.update(visible=False),
            "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        ]

    progress(0, desc="بدء التحليل...")

    def progress_callback(stage, message):
        progress(stage / 12, desc=message)

    try:
        analyzer = APKDeepAnalyzer(orig_file, mod_file, progress_callback)
        results = analyzer.analyze()
        _analysis_results = results

        if "error" in results:
            return [
                gr.update(visible=True, value=f"❌ خطأ: {results['error']}"),
                gr.update(visible=False), gr.update(visible=False),
                gr.update(visible=False), gr.update(visible=False),
                gr.update(visible=False), gr.update(visible=False),
                gr.update(visible=False), gr.update(visible=False),
                "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
            ]

        # Generate displays
        dashboard = create_dashboard(results)
        manifest_html = create_manifest_display(results)
        dex_html = create_dex_display(results)
        native_html = create_native_display(results)
        resources_html = create_resources_display(results)
        signature_html = create_signature_display(results)
        suspicious_html = create_suspicious_display(results)
        file_table = create_file_table(results)

        report_gen = ReportGenerator(results)
        txt_report = report_gen.generate_txt_report()
        json_report = report_gen.generate_json_report()
        html_report = report_gen.generate_html_report()

        progress(1.0, desc="اكتمل التحليل!")

        return [
            gr.update(visible=False),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            dashboard,
            manifest_html,
            dex_html,
            native_html,
            resources_html,
            signature_html,
            suspicious_html,
            file_table,
            txt_report,
            json_report,
            html_report,
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
        ]

    except Exception as e:
        return [
            gr.update(visible=True, value=f"❌ خطأ غير متوقع: {str(e)}"),
            gr.update(visible=False), gr.update(visible=False),
            gr.update(visible=False), gr.update(visible=False),
            gr.update(visible=False), gr.update(visible=False),
            gr.update(visible=False), gr.update(visible=False),
            "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        ]


def create_dashboard(data: dict) -> str:
    """Create dashboard HTML."""
    orig = data.get("original_info", {})
    mod = data.get("modified_info", {})
    summary = data.get("file_comparison", {}).get("summary", {})
    manifest = data.get("manifest_comparison", {}).get("changes", {})
    perms = manifest.get("permissions", {})
    dex = data.get("dex_analysis", {})
    native = data.get("native_libraries", {})
    sig = data.get("signature_comparison", {})

    html = f"""
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; padding: 10px;">
        <div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 12px; padding: 20px; border: 1px solid #0f3460;">
            <h4 style="color: #00d4ff; margin: 0 0 10px 0;">📦 APK الأصلي</h4>
            <p style="color: #eee; margin: 5px 0;">الحجم: <strong>{orig.get('size_formatted', 'N/A')}</strong></p>
            <p style="color: #888; font-size: 11px; word-break: break-all;">SHA-256: {orig.get('sha256', 'N/A')[:32]}...</p>
        </div>
        <div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 12px; padding: 20px; border: 1px solid #0f3460;">
            <h4 style="color: #ff6b6b; margin: 0 0 10px 0;">📦 APK المعدل</h4>
            <p style="color: #eee; margin: 5px 0;">الحجم: <strong>{mod.get('size_formatted', 'N/A')}</strong></p>
            <p style="color: #888; font-size: 11px; word-break: break-all;">SHA-256: {mod.get('sha256', 'N/A')[:32]}...</p>
        </div>
        <div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 12px; padding: 20px; border: 1px solid #0f3460;">
            <h4 style="color: #feca57; margin: 0 0 10px 0;">📊 إجمالي الملفات</h4>
            <p style="color: #4ecdc4; font-size: 32px; margin: 0;"><strong>{summary.get('total', 0)}</strong></p>
        </div>
        <div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 12px; padding: 20px; border: 1px solid #0f3460;">
            <h4 style="color: #48dbfb; margin: 0 0 10px 0;">✅ متطابقة</h4>
            <p style="color: #4ecdc4; font-size: 32px; margin: 0;"><strong>{summary.get('unchanged', 0)}</strong></p>
        </div>
        <div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 12px; padding: 20px; border: 1px solid #0f3460;">
            <h4 style="color: #feca57; margin: 0 0 10px 0;">⚠️ معدلة</h4>
            <p style="color: #feca57; font-size: 32px; margin: 0;"><strong>{summary.get('modified', 0)}</strong></p>
        </div>
        <div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 12px; padding: 20px; border: 1px solid #0f3460;">
            <h4 style="color: #4ecdc4; margin: 0 0 10px 0;">➕ مضافة</h4>
            <p style="color: #4ecdc4; font-size: 32px; margin: 0;"><strong>{summary.get('added', 0)}</strong></p>
        </div>
        <div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 12px; padding: 20px; border: 1px solid #0f3460;">
            <h4 style="color: #ff6b6b; margin: 0 0 10px 0;">➖ محذوفة</h4>
            <p style="color: #ff6b6b; font-size: 32px; margin: 0;"><strong>{summary.get('removed', 0)}</strong></p>
        </div>
        <div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 12px; padding: 20px; border: 1px solid #0f3460;">
            <h4 style="color: #ff9f43; margin: 0 0 10px 0;">🔐 التوقيع</h4>
            <p style="color: {'#ff6b6b' if sig.get('signature_changed') else '#4ecdc4'}; font-size: 18px; margin: 0;">
                <strong>{'تغير!' if sig.get('signature_changed') else 'متطابق'}</strong>
            </p>
        </div>
        <div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 12px; padding: 20px; border: 1px solid #0f3460;">
            <h4 style="color: #a29bfe; margin: 0 0 10px 0;">📋 ملفات DEX</h4>
            <p style="color: #eee; margin: 5px 0;">العدد: <strong>{dex.get('dex_count', 0)}</strong></p>
        </div>
        <div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 12px; padding: 20px; border: 1px solid #0f3460;">
            <h4 style="color: #fd79a8; margin: 0 0 10px 0;">🔧 Native Libs</h4>
            <p style="color: #eee; margin: 5px 0;">مضافة: <strong>{len(native.get('added', []))}</strong></p>
            <p style="color: #eee; margin: 5px 0;">محذوفة: <strong>{len(native.get('removed', []))}</strong></p>
        </div>
        <div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 12px; padding: 20px; border: 1px solid #0f3460;">
            <h4 style="color: #00b894; margin: 0 0 10px 0;">🔑 صلاحيات جديدة</h4>
            <p style="color: #4ecdc4; font-size: 24px; margin: 0;"><strong>{len(perms.get('added', []))}</strong></p>
        </div>
    </div>
    """
    return html


def create_manifest_display(data: dict) -> str:
    """Create manifest changes display."""
    manifest = data.get("manifest_comparison", {})
    changes = manifest.get("changes", {})

    html = '<div style="padding: 15px;">'
    html += '<h3 style="color: #00d4ff;">📋 تغييرات AndroidManifest.xml</h3>'

    # Package info
    pkg = changes.get("package_info", {})
    if pkg:
        html += '<h4 style="color: #feca57;">معلومات الحزمة:</h4><ul>'
        for key, vals in pkg.items():
            html += f'<li><code>{key}</code>: <span style="color: #ff6b6b;">{vals.get("original", "N/A")}</span> → <span style="color: #4ecdc4;">{vals.get("modified", "N/A")}</span></li>'
        html += '</ul>'

    # Permissions
    perms = changes.get("permissions", {})
    if perms.get("added"):
        html += '<h4 style="color: #4ecdc4;">➕ صلاحيات مضافة:</h4><ul>'
        for p in perms["added"]:
            html += f'<li style="color: #4ecdc4;">+ {p}</li>'
        html += '</ul>'

    if perms.get("removed"):
        html += '<h4 style="color: #ff6b6b;">➖ صلاحيات محذوفة:</h4><ul>'
        for p in perms["removed"]:
            html += f'<li style="color: #ff6b6b;">- {p}</li>'
        html += '</ul>'

    # Activities
    acts = changes.get("activities", {})
    if acts.get("added"):
        html += '<h4 style="color: #4ecdc4;">➕ Activities جديدة:</h4><ul>'
        for a in acts["added"]:
            html += f'<li style="color: #4ecdc4;">+ {a.get("name", "Unknown")}</li>'
        html += '</ul>'
    if acts.get("removed"):
        html += '<h4 style="color: #ff6b6b;">➖ Activities محذوفة:</h4><ul>'
        for a in acts["removed"]:
            html += f'<li style="color: #ff6b6b;">- {a.get("name", "Unknown")}</li>'
        html += '</ul>'

    # Services
    svcs = changes.get("services", {})
    if svcs.get("added"):
        html += '<h4 style="color: #4ecdc4;">➕ Services جديدة:</h4><ul>'
        for s in svcs["added"]:
            html += f'<li style="color: #4ecdc4;">+ {s.get("name", "Unknown")}</li>'
        html += '</ul>'
    if svcs.get("removed"):
        html += '<h4 style="color: #ff6b6b;">➖ Services محذوفة:</h4><ul>'
        for s in svcs["removed"]:
            html += f'<li style="color: #ff6b6b;">- {s.get("name", "Unknown")}</li>'
        html += '</ul>'

    # Receivers
    recs = changes.get("receivers", {})
    if recs.get("added"):
        html += '<h4 style="color: #4ecdc4;">➕ Receivers جديدة:</h4><ul>'
        for r in recs["added"]:
            html += f'<li style="color: #4ecdc4;">+ {r.get("name", "Unknown")}</li>'
        html += '</ul>'
    if recs.get("removed"):
        html += '<h4 style="color: #ff6b6b;">➖ Receivers محذوفة:</h4><ul>'
        for r in recs["removed"]:
            html += f'<li style="color: #ff6b6b;">- {r.get("name", "Unknown")}</li>'
        html += '</ul>'

    html += '</div>'
    return html


def create_dex_display(data: dict) -> str:
    """Create DEX analysis display."""
    dex = data.get("dex_analysis", {})

    html = '<div style="padding: 15px;">'
    html += '<h3 style="color: #00d4ff;">📊 تحليل ملفات DEX</h3>'

    comp = dex.get("comparison", {})
    html += f'<p>عدد ملفات DEX في الأصلي: <strong>{comp.get("original_count", 0)}</strong></p>'
    html += f'<p>عدد ملفات DEX في المعدل: <strong>{comp.get("modified_count", 0)}</strong></p>'

    if comp.get("added"):
        html += '<h4 style="color: #4ecdc4;">➕ DEX files مضافة:</h4><ul>'
        for f in comp["added"]:
            html += f'<li style="color: #4ecdc4;">+ {f}</li>'
        html += '</ul>'

    if comp.get("removed"):
        html += '<h4 style="color: #ff6b6b;">➖ DEX files محذوفة:</h4><ul>'
        for f in comp["removed"]:
            html += f'<li style="color: #ff6b6b;">- {f}</li>'
        html += '</ul>'

    # DEX file details
    html += '<h4 style="color: #feca57;">تفاصيل ملفات DEX:</h4>'
    for fname, fdata in dex.get("dex_files", {}).items():
        header = fdata.get("header", {})
        if "error" not in header:
            html += f'<div style="background: #16213e; padding: 10px; margin: 10px 0; border-radius: 8px;">'
            html += f'<strong>{fname}</strong><br>'
            html += f'Classes: {header.get("class_defs_count", "N/A")} | '
            html += f'Methods: {header.get("method_ids_count", "N/A")} | '
            html += f'Fields: {header.get("field_ids_count", "N/A")} | '
            html += f'Strings: {header.get("string_ids_count", "N/A")}'
            html += '</div>'

    # URLs
    urls = dex.get("all_urls", [])
    if urls:
        html += '<h4 style="color: #a29bfe;">🔗 URLs المستخرجة:</h4><ul>'
        for url in urls[:30]:
            html += f'<li><code>{url}</code></li>'
        if len(urls) > 30:
            html += f'<li style="color: #888;">... و {len(urls) - 30} أخرى</li>'
        html += '</ul>'

    # IPs
    ips = dex.get("all_ips", [])
    if ips:
        html += '<h4 style="color: #fd79a8;">🌐 عناوين IP:</h4><ul>'
        for ip in ips[:20]:
            html += f'<li><code>{ip}</code></li>'
        html += '</ul>'

    html += '</div>'
    return html


def create_native_display(data: dict) -> str:
    """Create native libraries display."""
    native = data.get("native_libraries", {})

    html = '<div style="padding: 15px;">'
    html += '<h3 style="color: #00d4ff;">🔧 مكتبات Native</h3>'

    if native.get("added"):
        html += '<h4 style="color: #4ecdc4;">➕ مكتبات مضافة:</h4><ul>'
        for lib in native["added"]:
            html += f'<li style="color: #4ecdc4;">+ {lib}</li>'
        html += '</ul>'

    if native.get("removed"):
        html += '<h4 style="color: #ff6b6b;">➖ مكتبات محذوفة:</h4><ul>'
        for lib in native["removed"]:
            html += f'<li style="color: #ff6b6b;">- {lib}</li>'
        html += '</ul>'

    if native.get("modified"):
        html += '<h4 style="color: #feca57;">⚠️ مكتبات معدلة:</h4><ul>'
        for lib in native["modified"]:
            html += f'<li style="color: #feca57;">~ {lib}</li>'
        html += '</ul>'

    if native.get("details"):
        html += '<h4 style="color: #feca57;">تفاصيل جميع المكتبات:</h4>'
        html += '<table style="width:100%; border-collapse: collapse;">'
        html += '<tr style="background: #0f3460;"><th style="padding: 8px; border: 1px solid #333;">المكتبة</th><th style="padding: 8px; border: 1px solid #333;">الحالة</th><th style="padding: 8px; border: 1px solid #333;">الحجم الأصلي</th><th style="padding: 8px; border: 1px solid #333;">الحجم المعدل</th></tr>'
        for detail in native["details"]:
            status_color = {"Added": "#4ecdc4", "Removed": "#ff6b6b", "Modified": "#feca57", "Unchanged": "#48dbfb"}.get(detail["status"], "#eee")
            html += f'<tr><td style="padding: 8px; border: 1px solid #333;">{detail["name"]}</td>'
            html += f'<td style="padding: 8px; border: 1px solid #333; color: {status_color};">{detail["status"]}</td>'
            html += f'<td style="padding: 8px; border: 1px solid #333;">{detail.get("original_size", "N/A")}</td>'
            html += f'<td style="padding: 8px; border: 1px solid #333;">{detail.get("modified_size", "N/A")}</td></tr>'
        html += '</table>'

    html += '</div>'
    return html


def create_resources_display(data: dict) -> str:
    """Create resources display."""
    res = data.get("resources", {})

    html = '<div style="padding: 15px;">'
    html += '<h3 style="color: #00d4ff;">🎨 الموارد (Resources)</h3>'

    res_data = res.get("res", {})
    orig_res = res_data.get("original", {})
    mod_res = res_data.get("modified", {})

    html += f'<p>ملفات res في الأصلي: <strong>{orig_res.get("count", 0)}</strong></p>'
    html += f'<p>ملفات res في المعدل: <strong>{mod_res.get("count", 0)}</strong></p>'

    assets_data = res.get("assets", {})
    orig_assets = assets_data.get("original", {})
    mod_assets = assets_data.get("modified", {})

    html += f'<p>ملفات assets في الأصلي: <strong>{orig_assets.get("count", 0)}</strong></p>'
    html += f'<p>ملفات assets في المعدل: <strong>{mod_assets.get("count", 0)}</strong></p>'

    arsc = res.get("resources_arsc", {})
    if arsc.get("original_exists") or arsc.get("modified_exists"):
        html += '<h4 style="color: #feca57;">resources.arsc:</h4>'
        html += f'<p>الأصلي: {"موجود" if arsc.get("original_exists") else "غير موجود"} ({arsc.get("original_size", 0):,} bytes)</p>'
        html += f'<p>المعدل: {"موجود" if arsc.get("modified_exists") else "غير موجود"} ({arsc.get("modified_size", 0):,} bytes)</p>'

    html += '</div>'
    return html


def create_signature_display(data: dict) -> str:
    """Create signature display."""
    sig = data.get("signature_comparison", {})

    html = '<div style="padding: 15px;">'
    html += '<h3 style="color: #00d4ff;">🔐 تحليل التوقيع</h3>'

    if sig.get("signature_changed"):
        html += '<div style="background: #ff6b6b22; border: 2px solid #ff6b6b; border-radius: 10px; padding: 15px; margin: 10px 0;">'
        html += '<h4 style="color: #ff6b6b;">⚠️ التوقيع تغير!</h4>'
        html += '<p>تم إعادة توقيع APK. هذا أمر طبيعي إذا تم تعديل التطبيق.</p>'
        html += '</div>'
    else:
        html += '<div style="background: #4ecdc422; border: 2px solid #4ecdc4; border-radius: 10px; padding: 15px; margin: 10px 0;">'
        html += '<h4 style="color: #4ecdc4;">✅ التوقيع متطابق</h4>'
        html += '<p>التوقيع الرقمي لم يتغير بين النسختين.</p>'
        html += '</div>'

    orig_sig = sig.get("original", {})
    mod_sig = sig.get("modified", {})

    html += '<h4 style="color: #feca57;">معلومات التوقيع الأصلي:</h4>'
    html += f'<p>V1 Signing: <strong>{"نعم" if orig_sig.get("has_v1_signing") else "لا"}</strong></p>'
    html += f'<p>V2 Signing: <strong>{"نعم" if orig_sig.get("has_v2_signing") else "لا"}</strong></p>'
    html += f'<p>V3 Signing: <strong>{"نعم" if orig_sig.get("has_v3_signing") else "لا"}</strong></p>'

    html += '<h4 style="color: #feca57;">معلومات التوقيع المعدل:</h4>'
    html += f'<p>V1 Signing: <strong>{"نعم" if mod_sig.get("has_v1_signing") else "لا"}</strong></p>'
    html += f'<p>V2 Signing: <strong>{"نعم" if mod_sig.get("has_v2_signing") else "لا"}</strong></p>'
    html += f'<p>V3 Signing: <strong>{"نعم" if mod_sig.get("has_v3_signing") else "لا"}</strong></p>'

    # Certificates
    orig_certs = orig_sig.get("certificates", [])
    if orig_certs:
        html += '<h4 style="color: #a29bfe;">الشهادات الأصلية:</h4><ul>'
        for cert in orig_certs:
            html += f'<li><code>{cert["filename"]}</code> - SHA-256: <code>{cert["sha256"][:32]}...</code></li>'
        html += '</ul>'

    html += '</div>'
    return html


def create_suspicious_display(data: dict) -> str:
    """Create suspicious changes display."""
    suspicious = data.get("suspicious_changes", [])

    html = '<div style="padding: 15px;">'
    html += '<h3 style="color: #ff6b6b;">⚠️ تغييرات مشبوهة محتملة</h3>'

    if not suspicious:
        html += '<div style="background: #4ecdc422; border: 2px solid #4ecdc4; border-radius: 10px; padding: 15px;">'
        html += '<p style="color: #4ecdc4;">✅ لم يتم اكتشاف تغييرات مشبوهة واضحة.</p>'
        html += '<p style="color: #888; font-size: 12px;">ملاحظة: هذا لا يعني أن التطبيق آمن 100%. يُنصح بالمراجعة اليدوية.</p>'
        html += '</div>'
    else:
        html += '<div style="background: #ff6b6b22; border: 2px solid #ff6b6b; border-radius: 10px; padding: 15px;">'
        html += '<p style="color: #ff6b6b;">⚠️ تم اكتشاف المؤشرات التالية (تتطلب مراجعة يدوية):</p>'
        html += '<ul>'
        for item in suspicious:
            html += f'<li style="color: #ff9f43; margin: 5px 0;">⚠️ {item}</li>'
        html += '</ul>'
        html += '<p style="color: #888; font-size: 12px;">ملاحظة: هذه المؤشرات لا تعني بالضرورة وجود تهديد. تتطلب مراجعة يدوية.</p>'
        html += '</div>'

    html += '</div>'
    return html


def create_file_table(data: dict) -> str:
    """Create detailed file comparison table."""
    details = data.get("file_comparison", {}).get("details", [])

    html = '<div style="padding: 15px;">'
    html += '<h3 style="color: #00d4ff;">📑 مقارنة تفصيلية للملفات</h3>'
    html += '<div style="max-height: 600px; overflow-y: auto;">'
    html += '<table style="width:100%; border-collapse: collapse; font-size: 12px;">'
    html += '<tr style="background: #0f3460; position: sticky; top: 0;">'
    html += '<th style="padding: 8px; border: 1px solid #333; text-align: left;">المسار</th>'
    html += '<th style="padding: 8px; border: 1px solid #333;">الحالة</th>'
    html += '<th style="padding: 8px; border: 1px solid #333;">حجم أصلي</th>'
    html += '<th style="padding: 8px; border: 1px solid #333;">حجم معدل</th>'
    html += '<th style="padding: 8px; border: 1px solid #333;">SHA-256 أصلي</th>'
    html += '<th style="padding: 8px; border: 1px solid #333;">SHA-256 معدل</th>'
    html += '</tr>'

    for detail in details:
        status = detail["status"]
        status_color = {
            "Added": "#4ecdc4",
            "Removed": "#ff6b6b",
            "Modified": "#feca57",
            "Unchanged": "#48dbfb"
        }.get(status, "#eee")

        orig_size = detail.get("original_size", 0)
        mod_size = detail.get("modified_size", 0)

        html += f'<tr>'
        html += f'<td style="padding: 6px; border: 1px solid #333; word-break: break-all;"><code>{detail["path"]}</code></td>'
        html += f'<td style="padding: 6px; border: 1px solid #333; color: {status_color}; text-align: center;"><strong>{status}</strong></td>'
        html += f'<td style="padding: 6px; border: 1px solid #333; text-align: right;">{orig_size:,}</td>'
        html += f'<td style="padding: 6px; border: 1px solid #333; text-align: right;">{mod_size:,}</td>'
        html += f'<td style="padding: 6px; border: 1px solid #333; font-size: 10px; word-break: break-all;"><code>{detail.get("original_sha256", "")[:16]}...</code></td>'
        html += f'<td style="padding: 6px; border: 1px solid #333; font-size: 10px; word-break: break-all;"><code>{detail.get("modified_sha256", "")[:16]}...</code></td>'
        html += '</tr>'

    html += '</table></div></div>'
    return html


def copy_report(report_text):
    """Return report for copying."""
    return report_text


def download_txt(report_text):
    """Prepare TXT download."""
    return report_text


def download_json(report_text):
    """Prepare JSON download."""
    return report_text


def download_html(report_text):
    """Prepare HTML download."""
    return report_text


# ==================== GRADIO UI ====================

css = """
:root {
    --primary: #00d4ff;
    --secondary: #ff6b6b;
    --accent: #feca57;
    --success: #4ecdc4;
    --bg: #1a1a2e;
    --card: #16213e;
    --border: #0f3460;
}
body {
    background: var(--bg) !important;
    color: #eee !important;
}
.gradio-container {
    background: var(--bg) !important;
}
.tabs {
    background: var(--card) !important;
    border-radius: 12px !important;
    border: 1px solid var(--border) !important;
}
.tab-nav {
    background: var(--card) !important;
    border-bottom: 2px solid var(--border) !important;
}
.tab-nav button {
    color: #eee !important;
    font-weight: bold !important;
}
.tab-nav button.selected {
    color: var(--primary) !important;
    border-bottom: 3px solid var(--primary) !important;
}
.upload-box {
    border: 2px dashed var(--border) !important;
    border-radius: 12px !important;
    background: var(--card) !important;
}
.upload-box:hover {
    border-color: var(--primary) !important;
}
.primary-btn {
    background: linear-gradient(135deg, var(--primary), #0099cc) !important;
    color: #000 !important;
    font-weight: bold !important;
    border: none !important;
    border-radius: 8px !important;
}
.primary-btn:hover {
    background: linear-gradient(135deg, #00e5ff, var(--primary)) !important;
}
.error-box {
    background: #ff6b6b22 !important;
    border: 2px solid var(--secondary) !important;
    border-radius: 10px !important;
    color: var(--secondary) !important;
}
.info-box {
    background: var(--card) !important;
    border: 1px solid var(--border) !important;
    border-radius: 10px !important;
    padding: 15px !important;
}
"""

with gr.Blocks(title="APK Deep Diff Analyzer") as demo:
    gr.Markdown("""
    <div style="text-align: center; padding: 20px;">
        <h1 style="color: #00d4ff; font-size: 2.5em; margin: 0;">🔍 APK Deep Diff Analyzer</h1>
        <p style="color: #888; font-size: 1.1em; margin: 10px 0;">
            أداة تحليل عميق ومقارنة احترافية لملفات Android APK
        </p>
        <p style="color: #666; font-size: 0.9em;">
            Professional APK Forensic Analysis & Deep Diff Tool
        </p>
    </div>
    """)

    # Error message
    error_msg = gr.Markdown(visible=False, elem_classes=["error-box"])

    with gr.Row():
        with gr.Column():
            gr.Markdown("### 📦 APK الأصلي (Original)")
            orig_upload = gr.File(
                label="",
                file_types=[".apk"],
                elem_classes=["upload-box"]
            )
            orig_info = gr.Markdown(elem_classes=["info-box"])

        with gr.Column():
            gr.Markdown("### 📦 APK المعدل (Modified)")
            mod_upload = gr.File(
                label="",
                file_types=[".apk"],
                elem_classes=["upload-box"]
            )
            mod_info = gr.Markdown(elem_classes=["info-box"])

    # Update file info on upload
    orig_upload.change(
        fn=update_file_info,
        inputs=[orig_upload],
        outputs=[orig_info]
    )
    mod_upload.change(
        fn=update_file_info,
        inputs=[mod_upload],
        outputs=[mod_info]
    )

    # Start analysis button
    analyze_btn = gr.Button(
        "🚀 بدء التحليل العميق | Start Deep Analysis",
        elem_classes=["primary-btn"],
        size="lg"
    )

    # Results tabs (initially hidden)
    with gr.Tabs(visible=False) as results_tabs:

        with gr.TabItem("📊 Dashboard"):
            dashboard_output = gr.HTML()

        with gr.TabItem("📋 Manifest"):
            manifest_output = gr.HTML()

        with gr.TabItem("📊 DEX Analysis"):
            dex_output = gr.HTML()

        with gr.TabItem("🔧 Native Libraries"):
            native_output = gr.HTML()

        with gr.TabItem("🎨 Resources"):
            resources_output = gr.HTML()

        with gr.TabItem("🔐 Signature"):
            signature_output = gr.HTML()

        with gr.TabItem("⚠️ Suspicious"):
            suspicious_output = gr.HTML()

        with gr.TabItem("📑 File Comparison"):
            file_table_output = gr.HTML()

        with gr.TabItem("📄 Reports"):
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### 📝 تقرير نصي (TXT)")
                    txt_report = gr.Textbox(
                        label="",
                        lines=20,
                        interactive=False
                    )
                    copy_txt_btn = gr.Button("📋 نسخ التقرير", visible=False)

                with gr.Column():
                    gr.Markdown("### 📊 تقرير JSON")
                    json_report = gr.Textbox(
                        label="",
                        lines=20,
                        interactive=False
                    )
                    copy_json_btn = gr.Button("📋 نسخ JSON", visible=False)

            with gr.Row():
                with gr.Column():
                    gr.Markdown("### 🌐 تقرير HTML")
                    html_report = gr.Textbox(
                        label="",
                        lines=20,
                        interactive=False
                    )
                    copy_html_btn = gr.Button("📋 نسخ HTML", visible=False)

    # Privacy notice
    gr.Markdown("""
    <div style="background: #16213e; border: 1px solid #0f3460; border-radius: 10px; padding: 15px; margin-top: 20px; text-align: center;">
        <p style="color: #888; font-size: 0.9em; margin: 0;">
            🔒 <strong>Privacy Notice:</strong> الملفات المرفوعة تُستخدم للتحليل فقط ولا تُحفظ على الخادم.
            <br>
            Uploaded files are used for analysis only and are not stored on the server.
        </p>
    </div>
    """)

    # Analysis button click
    analyze_btn.click(
        fn=run_analysis,
        inputs=[orig_upload, mod_upload],
        outputs=[
            error_msg,
            results_tabs,
            dashboard_output,
            manifest_output,
            dex_output,
            native_output,
            resources_output,
            signature_output,
            suspicious_output,
            file_table_output,
            txt_report,
            json_report,
            html_report,
            copy_txt_btn,
            copy_json_btn,
            copy_html_btn,
        ]
    )


if __name__ == "__main__":
    demo.launch(css=css, theme=gr.themes.Soft())