Spaces:
Running

File size: 29,724 Bytes
7fddf3d
 
 
54559aa
7fddf3d
 
 
 
dd1eee1
7fddf3d
 
 
 
 
567eb03
 
 
54559aa
567eb03
 
 
 
c43a9f9
 
567eb03
54559aa
dd1eee1
7fddf3d
 
 
 
 
 
 
 
 
 
 
54559aa
 
c43a9f9
54559aa
7fddf3d
 
54559aa
 
 
 
7fddf3d
 
 
54559aa
7fddf3d
 
567eb03
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
567eb03
 
 
 
 
 
 
 
 
 
54559aa
 
 
 
 
 
7fddf3d
 
 
 
 
 
 
 
 
 
54559aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fddf3d
 
 
 
 
54559aa
7fddf3d
 
54559aa
7fddf3d
 
 
 
 
 
 
 
 
 
54559aa
 
7fddf3d
54559aa
 
7fddf3d
54559aa
7fddf3d
54559aa
567eb03
54559aa
567eb03
54559aa
 
 
 
 
 
 
 
 
 
 
 
 
567eb03
54559aa
 
 
 
 
567eb03
7fddf3d
 
 
 
 
 
 
 
54559aa
7fddf3d
54559aa
7fddf3d
 
54559aa
7fddf3d
54559aa
567eb03
54559aa
567eb03
54559aa
 
 
 
 
 
 
 
 
 
 
 
 
567eb03
54559aa
 
 
 
 
567eb03
7fddf3d
 
 
 
 
 
 
 
54559aa
7fddf3d
54559aa
7fddf3d
 
54559aa
7fddf3d
54559aa
567eb03
54559aa
567eb03
54559aa
 
 
 
 
 
 
 
 
 
 
 
 
567eb03
54559aa
 
 
 
 
567eb03
7fddf3d
 
 
 
 
 
 
 
54559aa
7fddf3d
54559aa
7fddf3d
 
54559aa
567eb03
54559aa
567eb03
54559aa
 
 
 
 
 
 
 
 
 
 
 
 
567eb03
54559aa
 
 
 
 
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c43a9f9
 
 
f61206a
 
7fddf3d
 
 
c43a9f9
7fddf3d
dd1eee1
 
 
eb36037
 
 
dd1eee1
 
 
 
 
 
 
 
 
33dee12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1eee1
 
 
 
 
 
33dee12
dd1eee1
 
 
 
f61206a
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1eee1
7fddf3d
 
 
 
 
 
 
 
54559aa
7fddf3d
 
 
 
 
 
 
 
 
 
 
 
c43a9f9
 
7fddf3d
 
c43a9f9
7fddf3d
 
 
c43a9f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fddf3d
 
 
 
c43a9f9
7fddf3d
 
 
 
 
 
 
 
 
 
c43a9f9
 
 
 
 
dd1eee1
c43a9f9
 
 
dd1eee1
c43a9f9
 
 
dd1eee1
c43a9f9
 
 
 
 
dd1eee1
c43a9f9
 
 
 
 
 
dd1eee1
c43a9f9
 
 
 
 
 
 
 
dd1eee1
c43a9f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1eee1
c43a9f9
 
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
"""Unified API endpoint for analyzing all IOC types with source selection."""

import logging
from concurrent.futures import ThreadPoolExecutor, as_completed

from fastapi import APIRouter, File, Form, HTTPException, UploadFile

from src.exceptions import APIKeyMissingError, ExternalAPIError
from src.models.threat_context import MSSPSummaryRow
from src.models.unified import (
    SourceResult,
    UnifiedAnalysisResponse,
    UnifiedIOCResult,
)
from src.services import (
    AbuseIPDBService,
    MalwareBazaarService,
    OTXService,
    ThreatFoxService,
    URLhausService,
    URLScanService,
    VirusTotalService,
    context_aggregator,
    threat_analyzer,
)
from src.services.cache import cache
from src.services.stats import stats_service
from src.utils.helpers import get_country_name
from src.utils.ioc_detector import IOCType, detect_ioc_type
from src.utils.validators import (
    is_private_ip,
    parse_iocs_from_file,
    parse_iocs_from_text,
)

logger = logging.getLogger(__name__)
router = APIRouter()

# Thread pool for parallel API calls
MAX_PARALLEL_SOURCES = 8
MAX_PARALLEL_IOCS = 10  # Process up to 10 IOCs in parallel

# Available sources for each IOC type
IOC_SOURCE_MAP = {
    IOCType.IP: ["virustotal", "abuseipdb", "urlscan", "threatfox", "urlhaus", "otx"],
    IOCType.DOMAIN: ["virustotal", "urlscan", "threatfox", "urlhaus", "otx"],
    IOCType.URL: ["virustotal", "urlscan", "threatfox", "urlhaus", "otx"],
    IOCType.HASH: ["virustotal", "threatfox", "malwarebazaar", "otx"],
}



def _get_services(
    sources: list[str],
) -> dict[str, VirusTotalService | AbuseIPDBService | URLScanService | ThreatFoxService | URLhausService | MalwareBazaarService | None]:
    """Initialize requested services."""
    services = {}

    if "virustotal" in sources:
        try:
            services["virustotal"] = VirusTotalService()
        except APIKeyMissingError:
            services["virustotal"] = None

    if "abuseipdb" in sources:
        try:
            services["abuseipdb"] = AbuseIPDBService()
        except APIKeyMissingError:
            services["abuseipdb"] = None

    if "urlscan" in sources:
        try:
            services["urlscan"] = URLScanService()
        except APIKeyMissingError:
            services["urlscan"] = None

    # abuse.ch services - no API key required (optional key improves rate limits)
    if "threatfox" in sources:
        services["threatfox"] = ThreatFoxService()

    if "urlhaus" in sources:
        services["urlhaus"] = URLhausService()

    if "malwarebazaar" in sources:
        services["malwarebazaar"] = MalwareBazaarService()

    if "otx" in sources:
        try:
            services["otx"] = OTXService()
        except APIKeyMissingError:
            services["otx"] = None

    return services


def _close_services(services: dict) -> None:
    """Close all service connections."""
    for service in services.values():
        if service is not None:
            service.close()


# === Parallel Source Fetch Helpers ===

def _fetch_virustotal_ip(vt_service, ip: str) -> SourceResult:
    """Fetch VirusTotal data for IP."""
    if vt_service is None:
        return SourceResult(source="virustotal", available=False, error="API key not configured")
    try:
        cached = cache.get("virustotal", "ip", ip)
        if cached:
            return SourceResult(source="virustotal", data=cached)
        data = vt_service.analyze_ip(ip)
        cache.set("virustotal", "ip", ip, data)
        return SourceResult(source="virustotal", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="virustotal", error=str(e))


def _fetch_abuseipdb_ip(abuseipdb_service, ip: str) -> SourceResult:
    """Fetch AbuseIPDB data for IP."""
    if abuseipdb_service is None:
        return SourceResult(source="abuseipdb", available=False, error="API key not configured")
    try:
        cached = cache.get("abuseipdb", "ip", ip)
        if cached:
            return SourceResult(source="abuseipdb", data=cached)
        data = abuseipdb_service.check_ip(ip)
        if data.get("country_code"):
            data["country_name"] = get_country_name(data["country_code"])
        cache.set("abuseipdb", "ip", ip, data)
        return SourceResult(source="abuseipdb", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="abuseipdb", error=str(e))


def _fetch_urlscan_ip(urlscan_service, ip: str) -> SourceResult:
    """Fetch URLScan data for IP."""
    if urlscan_service is None:
        return SourceResult(source="urlscan", available=False, error="API key not configured")
    try:
        data = urlscan_service.search_ip(ip)
        return SourceResult(source="urlscan", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="urlscan", error=str(e))


def _fetch_threatfox(threatfox_service, ioc: str) -> SourceResult:
    """Fetch ThreatFox data for any IOC."""
    if threatfox_service is None:
        return SourceResult(source="threatfox", available=False, error="Service not available")
    try:
        data = threatfox_service.search_ioc(ioc)
        return SourceResult(source="threatfox", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="threatfox", error=str(e))


def _fetch_urlhaus_host(urlhaus_service, host: str) -> SourceResult:
    """Fetch URLhaus data for host (IP/Domain)."""
    if urlhaus_service is None:
        return SourceResult(source="urlhaus", available=False, error="Service not available")
    try:
        data = urlhaus_service.lookup_host(host)
        return SourceResult(source="urlhaus", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="urlhaus", error=str(e))


def _fetch_otx_ip(otx_service, ip: str) -> SourceResult:
    """Fetch OTX data for IP."""
    if otx_service is None:
        return SourceResult(source="otx", available=False, error="API key not configured")
    try:
        cached = cache.get("otx", "ip", ip)
        if cached:
            return SourceResult(source="otx", data=cached)
        data = otx_service.analyze_ip(ip)
        cache.set("otx", "ip", ip, data)
        return SourceResult(source="otx", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="otx", error=str(e))


# === Domain Parallel Helpers ===

def _fetch_virustotal_domain(vt_service, domain: str) -> SourceResult:
    """Fetch VirusTotal data for domain."""
    if vt_service is None:
        return SourceResult(source="virustotal", available=False, error="API key not configured")
    try:
        cached = cache.get("virustotal", "domain", domain)
        if cached:
            return SourceResult(source="virustotal", data=cached)
        data = vt_service.analyze_domain(domain)
        cache.set("virustotal", "domain", domain, data)
        return SourceResult(source="virustotal", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="virustotal", error=str(e))


def _fetch_urlscan_domain(urlscan_service, domain: str) -> SourceResult:
    """Fetch URLScan data for domain."""
    if urlscan_service is None:
        return SourceResult(source="urlscan", available=False, error="API key not configured")
    try:
        data = urlscan_service.search_domain(domain)
        return SourceResult(source="urlscan", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="urlscan", error=str(e))


def _fetch_otx_domain(otx_service, domain: str) -> SourceResult:
    """Fetch OTX data for domain."""
    if otx_service is None:
        return SourceResult(source="otx", available=False, error="API key not configured")
    try:
        cached = cache.get("otx", "domain", domain)
        if cached:
            return SourceResult(source="otx", data=cached)
        data = otx_service.analyze_domain(domain)
        cache.set("otx", "domain", domain, data)
        return SourceResult(source="otx", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="otx", error=str(e))


# === URL Parallel Helpers ===

def _fetch_virustotal_url(vt_service, url: str) -> SourceResult:
    """Fetch VirusTotal data for URL."""
    if vt_service is None:
        return SourceResult(source="virustotal", available=False, error="API key not configured")
    try:
        cached = cache.get("virustotal", "url", url)
        if cached:
            return SourceResult(source="virustotal", data=cached)
        data = vt_service.analyze_url(url)
        cache.set("virustotal", "url", url, data)
        return SourceResult(source="virustotal", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="virustotal", error=str(e))


def _fetch_urlscan_url(urlscan_service, url: str) -> SourceResult:
    """Fetch URLScan data for URL."""
    if urlscan_service is None:
        return SourceResult(source="urlscan", available=False, error="API key not configured")
    try:
        data = urlscan_service.search_url(url)
        return SourceResult(source="urlscan", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="urlscan", error=str(e))


def _fetch_urlhaus_url(urlhaus_service, url: str) -> SourceResult:
    """Fetch URLhaus data for URL."""
    if urlhaus_service is None:
        return SourceResult(source="urlhaus", available=False, error="Service not available")
    try:
        data = urlhaus_service.lookup_url(url)
        return SourceResult(source="urlhaus", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="urlhaus", error=str(e))


def _fetch_otx_url(otx_service, url: str) -> SourceResult:
    """Fetch OTX data for URL."""
    if otx_service is None:
        return SourceResult(source="otx", available=False, error="API key not configured")
    try:
        cached = cache.get("otx", "url", url)
        if cached:
            return SourceResult(source="otx", data=cached)
        data = otx_service.analyze_url(url)
        cache.set("otx", "url", url, data)
        return SourceResult(source="otx", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="otx", error=str(e))


# === Hash Parallel Helpers ===

def _fetch_virustotal_hash(vt_service, hash_val: str) -> SourceResult:
    """Fetch VirusTotal data for hash."""
    if vt_service is None:
        return SourceResult(source="virustotal", available=False, error="API key not configured")
    try:
        cached = cache.get("virustotal", "hash", hash_val)
        if cached:
            return SourceResult(source="virustotal", data=cached)
        data = vt_service.analyze_file_hash(hash_val)
        cache.set("virustotal", "hash", hash_val, data)
        return SourceResult(source="virustotal", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="virustotal", error=str(e))


def _fetch_malwarebazaar(malwarebazaar_service, hash_val: str) -> SourceResult:
    """Fetch MalwareBazaar data for hash."""
    if malwarebazaar_service is None:
        return SourceResult(source="malwarebazaar", available=False, error="Service not available")
    try:
        data = malwarebazaar_service.lookup_hash(hash_val)
        return SourceResult(source="malwarebazaar", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="malwarebazaar", error=str(e))


def _fetch_otx_hash(otx_service, hash_val: str) -> SourceResult:
    """Fetch OTX data for hash."""
    if otx_service is None:
        return SourceResult(source="otx", available=False, error="API key not configured")
    try:
        cached = cache.get("otx", "hash", hash_val)
        if cached:
            return SourceResult(source="otx", data=cached)
        data = otx_service.analyze_hash(hash_val)
        cache.set("otx", "hash", hash_val, data)
        return SourceResult(source="otx", data=data)
    except ExternalAPIError as e:
        return SourceResult(source="otx", error=str(e))


def _analyze_ip(
    ip: str,
    services: dict,
    requested_sources: list[str],
) -> dict[str, SourceResult]:
    """Analyze an IP address with requested sources IN PARALLEL."""
    results = {}

    # Check if private IP - skip all lookups
    if is_private_ip(ip):
        for source in requested_sources:
            if source in IOC_SOURCE_MAP[IOCType.IP]:
                results[source] = SourceResult(
                    source=source,
                    available=False,
                    error="Private/Reserved IP - API lookup skipped",
                )
        return results

    # Build list of tasks for parallel execution
    tasks = []

    if "virustotal" in requested_sources:
        tasks.append(("virustotal", _fetch_virustotal_ip, services.get("virustotal"), ip))
    if "abuseipdb" in requested_sources:
        tasks.append(("abuseipdb", _fetch_abuseipdb_ip, services.get("abuseipdb"), ip))
    if "urlscan" in requested_sources:
        tasks.append(("urlscan", _fetch_urlscan_ip, services.get("urlscan"), ip))
    if "threatfox" in requested_sources:
        tasks.append(("threatfox", _fetch_threatfox, services.get("threatfox"), ip))
    if "urlhaus" in requested_sources:
        tasks.append(("urlhaus", _fetch_urlhaus_host, services.get("urlhaus"), ip))
    if "otx" in requested_sources:
        tasks.append(("otx", _fetch_otx_ip, services.get("otx"), ip))

    # Execute all tasks in parallel
    with ThreadPoolExecutor(max_workers=MAX_PARALLEL_SOURCES) as executor:
        futures = {
            executor.submit(func, service, ioc): source_name
            for source_name, func, service, ioc in tasks
        }

        for future in as_completed(futures):
            source_name = futures[future]
            try:
                result = future.result()
                results[source_name] = result
            except Exception as e:
                logger.error(f"Parallel fetch error for {source_name}: {e}")
                results[source_name] = SourceResult(source=source_name, error=str(e))

    return results


def _analyze_domain(
    domain: str,
    services: dict,
    requested_sources: list[str],
) -> dict[str, SourceResult]:
    """Analyze a domain with requested sources IN PARALLEL."""
    results = {}
    tasks = []

    if "virustotal" in requested_sources:
        tasks.append(("virustotal", _fetch_virustotal_domain, services.get("virustotal"), domain))
    if "urlscan" in requested_sources:
        tasks.append(("urlscan", _fetch_urlscan_domain, services.get("urlscan"), domain))
    if "threatfox" in requested_sources:
        tasks.append(("threatfox", _fetch_threatfox, services.get("threatfox"), domain))
    if "urlhaus" in requested_sources:
        tasks.append(("urlhaus", _fetch_urlhaus_host, services.get("urlhaus"), domain))
    if "otx" in requested_sources:
        tasks.append(("otx", _fetch_otx_domain, services.get("otx"), domain))

    # Execute all tasks in parallel
    with ThreadPoolExecutor(max_workers=MAX_PARALLEL_SOURCES) as executor:
        futures = {
            executor.submit(func, service, ioc): source_name
            for source_name, func, service, ioc in tasks
        }

        for future in as_completed(futures):
            source_name = futures[future]
            try:
                result = future.result()
                results[source_name] = result
            except Exception as e:
                logger.error(f"Parallel fetch error for {source_name}: {e}")
                results[source_name] = SourceResult(source=source_name, error=str(e))

    return results


def _analyze_url(
    url: str,
    services: dict,
    requested_sources: list[str],
) -> dict[str, SourceResult]:
    """Analyze a URL with requested sources IN PARALLEL."""
    results = {}
    tasks = []

    if "virustotal" in requested_sources:
        tasks.append(("virustotal", _fetch_virustotal_url, services.get("virustotal"), url))
    if "urlscan" in requested_sources:
        tasks.append(("urlscan", _fetch_urlscan_url, services.get("urlscan"), url))
    if "threatfox" in requested_sources:
        tasks.append(("threatfox", _fetch_threatfox, services.get("threatfox"), url))
    if "urlhaus" in requested_sources:
        tasks.append(("urlhaus", _fetch_urlhaus_url, services.get("urlhaus"), url))
    if "otx" in requested_sources:
        tasks.append(("otx", _fetch_otx_url, services.get("otx"), url))

    # Execute all tasks in parallel
    with ThreadPoolExecutor(max_workers=MAX_PARALLEL_SOURCES) as executor:
        futures = {
            executor.submit(func, service, ioc): source_name
            for source_name, func, service, ioc in tasks
        }

        for future in as_completed(futures):
            source_name = futures[future]
            try:
                result = future.result()
                results[source_name] = result
            except Exception as e:
                logger.error(f"Parallel fetch error for {source_name}: {e}")
                results[source_name] = SourceResult(source=source_name, error=str(e))

    return results


def _analyze_hash(
    hash_value: str,
    services: dict,
    requested_sources: list[str],
) -> dict[str, SourceResult]:
    """Analyze a file hash with requested sources IN PARALLEL."""
    results = {}
    tasks = []

    if "virustotal" in requested_sources:
        tasks.append(("virustotal", _fetch_virustotal_hash, services.get("virustotal"), hash_value))
    if "threatfox" in requested_sources:
        tasks.append(("threatfox", _fetch_threatfox, services.get("threatfox"), hash_value))
    if "malwarebazaar" in requested_sources:
        tasks.append(("malwarebazaar", _fetch_malwarebazaar, services.get("malwarebazaar"), hash_value))
    if "otx" in requested_sources:
        tasks.append(("otx", _fetch_otx_hash, services.get("otx"), hash_value))

    # Execute all tasks in parallel
    with ThreadPoolExecutor(max_workers=MAX_PARALLEL_SOURCES) as executor:
        futures = {
            executor.submit(func, service, ioc): source_name
            for source_name, func, service, ioc in tasks
        }

        for future in as_completed(futures):
            source_name = futures[future]
            try:
                result = future.result()
                results[source_name] = result
            except Exception as e:
                logger.error(f"Parallel fetch error for {source_name}: {e}")
                results[source_name] = SourceResult(source=source_name, error=str(e))

    return results


def _analyze_single_ioc(
    value: str,
    ioc_type: IOCType,
    services: dict,
    requested_sources: list[str],
) -> UnifiedIOCResult:
    """Analyze a single IOC based on its detected type."""
    # Filter sources to only those available for this IOC type
    available_sources = IOC_SOURCE_MAP.get(ioc_type, [])
    sources_to_use = [s for s in requested_sources if s in available_sources]

    # Handle unknown IOC type
    if ioc_type == IOCType.UNKNOWN:
        return UnifiedIOCResult(
            value=value,
            detected_type=ioc_type,
            sources={
                "error": SourceResult(
                    source="detection",
                    available=False,
                    error="Could not determine IOC type",
                )
            },
        )

    # Route to appropriate analyzer
    if ioc_type == IOCType.IP:
        source_results = _analyze_ip(value, services, sources_to_use)
    elif ioc_type == IOCType.DOMAIN:
        source_results = _analyze_domain(value, services, sources_to_use)
    elif ioc_type == IOCType.URL:
        source_results = _analyze_url(value, services, sources_to_use)
    elif ioc_type == IOCType.HASH:
        source_results = _analyze_hash(value, services, sources_to_use)
    else:
        source_results = {}

    # Aggregate threat context from all sources
    threat_context = context_aggregator.aggregate(source_results)

    # Build result object
    result = UnifiedIOCResult(
        value=value,
        detected_type=ioc_type,
        sources=source_results,
        threat_context=threat_context,
    )

    # Determine verdict for stats logging
    verdict = "unknown"
    if ioc_type == IOCType.IP and is_private_ip(value):
        verdict = "private ip"
    elif threat_context:
        # Use the aggregated threat context to determine verdict
        # Check for malicious indicators: malware families indicate known malware
        if threat_context.malware_families:
            verdict = "malicious"
        elif threat_context.threat_actors:
            verdict = "suspicious"
        elif any(sr.data and sr.data.get("status") == "clean" for sr in source_results.values()):
            verdict = "clean"

    # Extract country_code from source results for geo stats
    country_code = None
    if ioc_type == IOCType.IP:
        # Priority: AbuseIPDB > OTX > VirusTotal > URLScan
        for src_key, field in [
            ("abuseipdb", "country_code"),
            ("otx", "country_code"),
            ("virustotal", "country"),
        ]:
            sr = source_results.get(src_key)
            if sr and sr.data:
                country_code = sr.data.get(field)
            if country_code:
                break
        if not country_code:
            sr = source_results.get("urlscan")
            if sr and sr.data:
                results_list = sr.data.get("results", [])
                if results_list:
                    country_code = results_list[0].get("country")

    elif ioc_type in (IOCType.DOMAIN, IOCType.URL):
        # URLScan provides hosting server country for domains/URLs
        sr = source_results.get("urlscan")
        if sr and sr.data:
            results_list = sr.data.get("results", [])
            if results_list:
                country_code = results_list[0].get("country")

    elif ioc_type == IOCType.HASH:
        # MalwareBazaar provides origin_country for hashes
        sr = source_results.get("malwarebazaar")
        if sr and sr.data:
            country_code = sr.data.get("origin_country")

    # Log to stats (synchronous, non-blocking in separate thread context)
    try:
        stats_service.log_lookup(
            ioc_value=value,
            ioc_type=ioc_type.value,
            verdict=verdict,
            country_code=country_code,
        )
    except Exception:
        pass  # Don't let stats logging break the main flow

    return result


@router.post("/analyze", response_model=UnifiedAnalysisResponse)
async def analyze_unified(
    text_input: str | None = Form(
        None, description="IOCs (comma or newline separated) - auto-detected"
    ),
    file: UploadFile | None = File(
        None, description="TXT file containing IOCs, one per line"
    ),
    sources: str = Form(
        "virustotal,abuseipdb,urlscan",
        description="Comma-separated list of sources to query",
    ),
):
    """
    Analyze IOCs with automatic type detection and source selection.

    Supports IP addresses, domains, URLs, and file hashes.
    The backend automatically detects the IOC type and routes to appropriate APIs.

    Args:
        text_input: IOCs (comma or newline separated)
        file: TXT file containing IOCs (one per line)
        sources: Comma-separated list of sources (virustotal, abuseipdb, urlscan)

    Returns:
        UnifiedAnalysisResponse with results from all requested sources
    """
    # Validate input
    if not text_input and not file:
        raise HTTPException(
            status_code=400,
            detail="Please provide either text_input or file. Both cannot be empty.",
        )

    # Parse IOCs from input
    iocs: list[str] = []

    if text_input:
        iocs.extend(parse_iocs_from_text(text_input))

    if file:
        if not file.filename or not file.filename.lower().endswith(".txt"):
            raise HTTPException(
                status_code=400,
                detail="File must be a .txt file",
            )
        content = await file.read()
        file_content = content.decode("utf-8-sig")
        iocs.extend(parse_iocs_from_file(file_content))

    if not iocs:
        raise HTTPException(
            status_code=400,
            detail="No IOCs found in input",
        )

    # Remove duplicates while preserving order
    seen: set[str] = set()
    unique_iocs: list[str] = []
    for ioc in iocs:
        if ioc.lower() not in seen:
            seen.add(ioc.lower())
            unique_iocs.append(ioc)

    # Enforce maximum IOC limit
    MAX_IOCS = 100
    if len(unique_iocs) > MAX_IOCS:
        raise HTTPException(
            status_code=400,
            detail=f"Maximum {MAX_IOCS} IOCs per request. You submitted {len(unique_iocs)} unique IOCs. Please reduce the number of IOCs and try again.",
        )

    # Parse requested sources
    requested_sources = [s.strip().lower() for s in sources.split(",") if s.strip()]
    valid_sources = ["virustotal", "abuseipdb", "urlscan", "threatfox", "urlhaus", "malwarebazaar", "otx"]
    requested_sources = [s for s in requested_sources if s in valid_sources]

    if not requested_sources:
        requested_sources = valid_sources

    # Initialize services
    services = _get_services(requested_sources)

    try:
        results: list[UnifiedIOCResult] = []
        type_counts: dict[str, int] = {}

        # Pre-detect IOC types and count them (fast operation)
        ioc_type_map = {}
        for ioc in unique_iocs:
            ioc_type = detect_ioc_type(ioc)
            ioc_type_map[ioc] = ioc_type
            type_name = ioc_type.value
            type_counts[type_name] = type_counts.get(type_name, 0) + 1

        # === PARALLEL IOC PROCESSING ===
        # Process ALL IOCs in parallel (up to MAX_PARALLEL_IOCS)
        # This is the critical optimization - instead of waiting for each IOC sequentially,
        # we process them all at once. Each IOC still fetches its sources in parallel internally.
        with ThreadPoolExecutor(max_workers=MAX_PARALLEL_IOCS) as executor:
            futures = {
                executor.submit(
                    _analyze_single_ioc, ioc, ioc_type_map[ioc], services, requested_sources
                ): ioc
                for ioc in unique_iocs
            }

            for future in as_completed(futures):
                ioc = futures[future]
                try:
                    result = future.result()
                    results.append(result)
                except Exception as e:
                    logger.error(f"Error analyzing IOC {ioc}: {e}")
                    # Create error result for failed IOC
                    results.append(UnifiedIOCResult(
                        value=ioc,
                        detected_type=ioc_type_map[ioc],
                        sources={"error": SourceResult(
                            source="error",
                            available=False,
                            error=str(e),
                        )},
                    ))

        # Generate MSSP summary table
        mssp_summary = _generate_mssp_summary(results)

        return UnifiedAnalysisResponse(
            results=results,
            summary=type_counts,
            mssp_summary=mssp_summary,
        )

    except Exception as e:
        logger.error(f"Error processing IOCs: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"Error processing IOCs: {str(e)}",
        ) from e
    finally:
        _close_services(services)


def _generate_mssp_summary(results: list[UnifiedIOCResult]) -> list[MSSPSummaryRow]:
    """
    Generate MSSP executive summary table from analysis results.

    This creates a structured, exportable table suitable for customer reports.
    """
    mssp_rows = []

    for result in results:
        # Get threat context
        ctx = result.threat_context

        # Build source data dict for threat analyzer
        source_data = {}
        for source_name, source_result in result.sources.items():
            if source_result.data:
                source_data[source_name] = {"data": source_result.data}

        # Run deterministic threat analysis
        threat_result = threat_analyzer.analyze(
            result.value,
            result.detected_type.value,
            source_data,
        )

        # Determine which sources had positive detections
        sources_detected = []
        for source_name, source_result in result.sources.items():
            if source_result.data and source_result.data.get("found"):
                # Check if it's a positive detection
                status = source_result.data.get("status", "")
                if status in ["malicious", "suspicious"]:
                    sources_detected.append(source_name)

        # Build MSSP row
        row = MSSPSummaryRow(
            ioc=result.value,
            ioc_type=result.detected_type.value,
            verdict=threat_result.verdict,
            risk_level=threat_result.risk_level,
            risk_score=threat_result.risk_score,
            threat_actor=ctx.threat_actors[0] if ctx and ctx.threat_actors else None,
            malware_family=ctx.malware_families[0] if ctx and ctx.malware_families else None,
            mitre_techniques=ctx.mitre_techniques[:5] if ctx else [],
            first_seen=ctx.first_seen if ctx else None,
            last_seen=ctx.last_seen if ctx else None,
            sources_detected=sources_detected,
            detection_count=len(sources_detected),
            recommended_action=threat_result.recommendations[0] if threat_result.recommendations else "Monitor",
            confidence=ctx.confidence if ctx else "unknown",
        )
        mssp_rows.append(row)

    return mssp_rows