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
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
import requests
from bs4 import BeautifulSoup, FeatureNotFound
from urllib.parse import urljoin, urlparse, parse_qs, unquote, quote, urlunparse
from collections import deque
import csv
import datetime
import re
import time
from io import StringIO
import json
import hashlib
import html
import logging
import tldextract
from urllib3.util import Retry
from requests.adapters import HTTPAdapter
import threading

class EnhancedWebCrawler:
    def __init__(self, start_url, crawl_mode="Standard", keywords=None, status_callback=None, progress_callback=None, result_callback=None):
        self.session = self._create_session()
        self.start_url = start_url
        self.keywords = keywords if keywords else ["gowithguide", "go with guide", "go-with-guide"]
        self.main_domain = urlparse(start_url).netloc
        self.crawl_mode = crawl_mode
        self.max_pages = {"Quick": 5, "Standard": 150, "Complete": 5000}[crawl_mode]
        self.visited = set()
        self.results = []
        self.queue = deque([start_url])
        self.categories = []
        self.current_category = None
        self.status_messages = []
        self.user_stopped = False
        self.pages_crawled = 0
        self.redirect_cache = {}
        self.internal_links = set()
        self.known_shorteners = [
            'bit.ly', 'tinyurl.com', 'goo.gl', 't.co', 'ow.ly', 'is.gd',
            'buff.ly', 'adf.ly', 'bit.do', 'mcaf.ee', 'su.pr', 'tiny.cc',
            'tidd.ly', 'redirectingat.com', 'go.redirectingat.com', 'go.skimresources.com'
        ]
        self.awin_domains = ['awin1.com', 'zenaps.com']
        self.potential_affiliate_domains = [
            'track.', 'go.', 'click.', 'buy.', 'shop.', 'link.', 'visit.',
            'affiliate.', 'partners.', 'tracking.', 'redirect.', 'ref.'
        ]
        self.potential_affiliate_paths = [
            '/visit', '/go', '/goto', '/redirect', '/click', '/buy', '/shop',
            '/link', '/affiliate', '/partner', '/tracking', '/ref', '/out'
        ]
        self.potential_affiliate_params = [
            'site', 'url', 'link', 'goto', 'target', 'redirect', 'redirect_to',
            'dest', 'destination', 'u', 'to', 'out', 'away', 'href'
        ]
        self.crawled_pages_content = {}
        self.url_fragments_checked = set()
        self.status_callback = status_callback
        self.progress_callback = progress_callback
        self.result_callback = result_callback
        self.setup_logger()

    def setup_logger(self):
        self.logger = logging.getLogger('crawler')
        self.logger.setLevel(logging.INFO)
        if not self.logger.handlers:
            handler = logging.StreamHandler()
            formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
            handler.setFormatter(formatter)
            self.logger.addHandler(handler)

    def _create_session(self):
        session = requests.Session()
        retries = Retry(
            total=3,
            backoff_factor=0.5,
            status_forcelist=[429, 500, 502, 503, 504],
            allowed_methods=["GET", "HEAD"]
        )
        adapter = HTTPAdapter(max_retries=retries)
        session.mount("http://", adapter)
        session.mount("https://", adapter)
        session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
            'Cache-Control': 'max-age=0'
        })
        return session

    def get_soup(self, html_content):
        try:
            return BeautifulSoup(html_content, 'lxml')
        except FeatureNotFound:
            return BeautifulSoup(html_content, 'html.parser')

    def is_same_domain(self, url):
        main_domain_parts = tldextract.extract(self.start_url)
        url_domain_parts = tldextract.extract(url)
        return (main_domain_parts.domain == url_domain_parts.domain and
                main_domain_parts.suffix == url_domain_parts.suffix)

    def is_subdomain_of(self, url_netloc):
        main_domain = self.main_domain.replace("www.", "").lower()
        url_netloc = url_netloc.replace("www.", "").lower()
        return url_netloc.endswith("." + main_domain) or url_netloc == main_domain

    def is_relevant_path(self, url):
        parsed_url = urlparse(url)
        path = parsed_url.path.lower()
        if re.search(r'\.(jpg|jpeg|png|gif|svg|pdf|zip|rar|css|js|xml|json)$', path):
            return False
        if re.search(r'/(login|logout|register|signin|signout|cart|checkout|privacy|terms)/?$', path):
            return False
        if re.search(r'/(post|article|blog|news|story|travel|guide|destination|affiliate)/', path):
            return True
        if len(parse_qs(parsed_url.query)) > 3:
            return False
        return True

    def normalize_url(self, url):
        parsed = urlparse(url)
        normalized = urlunparse((parsed.scheme, parsed.netloc, parsed.path,
                                parsed.params, parsed.query, ''))
        if normalized.endswith('/'):
            normalized = normalized[:-1]
        return normalized

    def looks_like_affiliate_url(self, url):
        url_lower = url.lower()
        parsed_url = urlparse(url_lower)
        netloc = parsed_url.netloc
        path = parsed_url.path

        if any(shortener in netloc for shortener in self.known_shorteners):
            return True
        if any(tracker in netloc for tracker in self.potential_affiliate_domains):
            return True
        if any(domain in netloc for domain in self.awin_domains):
            query_params = parse_qs(parsed_url.query)
            if 'v' in query_params and query_params['v'][0] == '87121':
                return True
            if 'awinmid' in query_params and query_params['awinmid'][0] == '87121':
                return True
        if any(aff_path in path for aff_path in self.potential_affiliate_paths):
            return True
        query_params = parse_qs(parsed_url.query)
        affiliate_params = ['aff', 'affid', 'affiliateid', 'ref', 'refid', 'referral',
                           'referralid', 'partner', 'partnerId', 'utm_source']
        for param in affiliate_params:
            if param in query_params:
                return True
        for param in self.potential_affiliate_params:
            if param in query_params:
                param_value = query_params[param][0].lower()
                if any(keyword in param_value for keyword in self.keywords):
                    return True
        tracking_params = ['utm_', 'ref', 'aff', 'source', 'campaign', 'medium']
        tracking_count = sum(1 for param in query_params if any(t in param for t in tracking_params))
        if tracking_count >= 2:
            return True
        if 'awc' in query_params:
            awc_value = query_params['awc'][0]
            if '87121' in awc_value:
                return True
        return False

    def extract_redirection_url(self, html_content, url):
        soup = self.get_soup(html_content)
        redirect_urls = []
        meta_refresh = soup.find('meta', attrs={'http-equiv': re.compile('^refresh$', re.I)})
        if meta_refresh and meta_refresh.get('content'):
            match = re.search(r'url=(.+)', meta_refresh['content'], re.I)
            if match:
                redirect_url = match.group(1).strip()
                redirect_urls.append(urljoin(url, redirect_url))
        script_patterns = [
            r'window\.location(?:\.href)?\s*=\s*[\'"](.+?)[\'"]',
            r'window\.location\.replace\([\'"](.+?)[\'"]\)',
            r'window\.open\([\'"](.+?)[\'"]\)',
            r'location\.href\s*=\s*[\'"](.+?)[\'"]',
            r'location\.replace\([\'"](.+?)[\'"]\)',
            r'setTimeout\([\'"]window\.location\.href=[\'"](.+?)[\'"][\'"]',
            r'url:\s*[\'"](.+?)[\'"]',
            r'href=[\'"](.+?)[\'"]'
        ]
        scripts = soup.find_all('script')
        for script in scripts:
            if script.string:
                for pattern in script_patterns:
                    matches = re.findall(pattern, script.string)
                    for match in matches:
                        if len(match) > 10:
                            redirect_urls.append(urljoin(url, match))
        parsed_url = urlparse(url)
        query_params = parse_qs(parsed_url.query)
        redirect_params = ['redirect_to', 'redirect', 'url', 'link', 'goto', 'target', 'ued']
        for param in redirect_params:
            if param in query_params:
                decoded_url = unquote(query_params[param][0])
                redirect_urls.append(urljoin(url, decoded_url))
        return redirect_urls

    def check_url_for_keywords(self, url, source_url):
        if not url or not isinstance(url, str):
            return
        url_hash = hashlib.md5(url.encode()).hexdigest()
        if url_hash in self.url_fragments_checked:
            return
        self.url_fragments_checked.add(url_hash)
        matched_kws = self.get_matched_keywords(url)
        if matched_kws:
            self.add_result(
                source_url=source_url,
                matched_url=url,
                element='url',
                attribute='href',
                content=url,
                keywords=matched_kws,
                location_type='direct_url'
            )
        if self.looks_like_affiliate_url(url):
            final_url, history = self.resolve_redirects(url)
            if final_url != url:
                matched_kws_final = self.get_matched_keywords(final_url)
                if matched_kws_final:
                    self.add_result(
                        source_url=source_url,
                        matched_url=final_url,
                        element='url',
                        attribute='href',
                        content=f"Redirected from: {url} to: {final_url}",
                        keywords=matched_kws_final,
                        location_type='redirected_url'
                    )
            for intermediate_url in history:
                matched_kws_intermediate = self.get_matched_keywords(intermediate_url)
                if matched_kws_intermediate:
                    self.add_result(
                        source_url=source_url,
                        matched_url=intermediate_url,
                        element='url',
                        attribute='href',
                        content=f"Redirect chain URL: {intermediate_url}",
                        keywords=matched_kws_intermediate,
                        location_type='redirect_chain_url'
                    )

    def get_matched_keywords(self, text):
        if not text or not isinstance(text, str):
            return []
        matched = []
        text_lower = text.lower()
        for keyword in self.keywords:
            if keyword.lower() in text_lower:
                matched.append(keyword)
        return matched

    def add_result(self, source_url, matched_url, element, attribute, content, keywords, location_type):
        result = {
            'source_url': source_url,
            'matched_url': matched_url,
            'keyword': ', '.join(keywords),
            'location_type': location_type,
            'element': element,
            'attribute': attribute,
            'content': content,
            'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        self.results.append(result)
        if self.result_callback:
            self.result_callback(result)
        if self.status_callback:
            self.status_callback(f"Found match: {matched_url} (Keyword: {result['keyword']})")

    def resolve_redirects(self, url):
        if url in self.redirect_cache:
            return self.redirect_cache[url]
        history = []
        final_url = url
        try:
            response = self.session.head(url, allow_redirects=True, timeout=5)
            if response.history:
                history = [resp.url for resp in response.history]
                final_url = response.url
            self.redirect_cache[url] = (final_url, history)
        except requests.RequestException:
            self.redirect_cache[url] = (url, [])
        return self.redirect_cache[url]

    def process_url(self, url):
        if url in self.visited or self.pages_crawled >= self.max_pages or not url or self.user_stopped:
            return []
        self.visited.add(url)
        self.pages_crawled += 1
        if self.progress_callback:
            self.progress_callback(self.pages_crawled / self.max_pages)
        try:
            response = self.session.get(
                url,
                headers={
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                    'Accept': 'text/html,application/xhtml+xml,application/xml'
                },
                timeout=20,
                allow_redirects=True
            )
            response.raise_for_status()
            content_type = response.headers.get('content-type', '').lower()
            if 'text/html' not in content_type:
                return []
            html_content = response.text
            # self.crawled_pages_content[url] = html_content  # REMOVED: Memory leak
            soup = self.get_soup(html_content)
            matched_kws = self.get_matched_keywords(html_content)
            if matched_kws:
                self.add_result(
                    source_url=url,
                    matched_url=url,
                    element='page_content',
                    attribute='text',
                    content=html_content[:200],
                    keywords=matched_kws,
                    location_type='content'
                )
            redirect_urls = self.extract_redirection_url(html_content, url)
            for redirect_url in redirect_urls:
                self.check_url_for_keywords(redirect_url, url)
            links = []
            for a_tag in soup.find_all('a', href=True):
                href = a_tag.get('href')
                if not href:
                    continue
                absolute_url = urljoin(url, href)
                absolute_url = self.normalize_url(absolute_url)
                if (self.is_same_domain(absolute_url) or self.is_subdomain_of(urlparse(absolute_url).netloc)) and self.is_relevant_path(absolute_url):
                    links.append(absolute_url)
                    self.internal_links.add(absolute_url)
                self.check_url_for_keywords(absolute_url, url)
            return links
        except requests.RequestException as e:
            status_code = e.response.status_code if (e.response is not None) else None
            error_message = self.get_user_friendly_error(status_code, url)
            self.logger.warning(error_message)
            if self.status_callback:
                self.status_callback(error_message)
            return []

    def get_user_friendly_error(self, status_code, url):
        error_messages = {
            400: "Bad Request",
            401: "Unauthorized",
            403: "Forbidden",
            404: "URL not found",
            500: "Internal Server Error",
            502: "Bad Gateway",
            503: "Service Unavailable",
            504: "Gateway Timeout",
        }
        if status_code is None:
            message = "Connection error"
        else:
            message = error_messages.get(status_code, f"HTTP {status_code}")
        return f"{message} for URL: {url}"

    def start_crawling(self):
        self.reset_state()
        if self.status_callback:
            self.status_callback(f"Starting crawl of {self.start_url} in {self.crawl_mode} mode")
        while self.queue and not self.user_stopped and self.pages_crawled < self.max_pages:
            url = self.queue.popleft()
            new_urls = self.process_url(url)
            for new_url in new_urls:
                if (new_url not in self.visited and new_url not in self.queue and
                        self.pages_crawled < self.max_pages):
                    self.queue.append(new_url)
            if self.progress_callback:
                self.progress_callback(min(self.pages_crawled / self.max_pages, 1.0))
            if self.results:
                if self.status_callback:
                    self.status_callback(f"Found {len(self.results)} matches")
        if self.status_callback:
            self.status_callback("Crawling completed")
        return self.results

    def reset_state(self):
        self.visited = set()
        self.queue = deque([self.start_url])
        self.results = []
        self.pages_crawled = 0
        self.redirect_cache = {}
        self.internal_links = set()
        # self.crawled_pages_content = {}  # REMOVED: Memory leak
        self.url_fragments_checked = set()


def _ddg_search_via_library(query, max_results=30):
    results = []
    ddgs_module = None
    for pkg in ('ddgs', 'duckduckgo_search'):
        try:
            mod = __import__(pkg, fromlist=['DDGS'])
            ddgs_module = getattr(mod, 'DDGS')
            break
        except (ImportError, AttributeError):
            continue
    if ddgs_module is None:
        raise ImportError("Neither 'ddgs' nor 'duckduckgo_search' library is installed.")
    with ddgs_module() as ddgs:
        for r in ddgs.text(query, max_results=max_results):
            results.append({
                'title':   r.get('title', ''),
                'url':     r.get('href', r.get('url', '')),
                'snippet': r.get('body', r.get('snippet', ''))
            })
    return results

def _ddg_search_via_html(query, max_results=30):
    """Fallback: scrape DuckDuckGo HTML search results with rotating User-Agent and retries.
    Tries multiple DuckDuckGo HTML endpoints and retries on failures to improve reliability when behind cloud IPs.
    """
    import random, time
    results = []
    session = requests.Session()
    USER_AGENTS = [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Safari/605.1.15',
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
    ]
    session.headers.update({
        'User-Agent': random.choice(USER_AGENTS),
        'Accept-Language': 'en-US,en;q=0.9',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Referer': 'https://duckduckgo.com/',
    })
    # DuckDuckGo provides two HTML endpoints that can be used.
    endpoints = [
        'https://html.duckduckgo.com/html/',
        'https://duckduckgo.com/html/',
    ]
    params = {'q': query, 'kl': 'us-en'}
    max_attempts = 3
    for base_url in endpoints:
        attempt = 0
        while attempt < max_attempts:
            try:
                response = session.get(base_url, params=params, timeout=20)
                response.raise_for_status()
                soup = BeautifulSoup(response.text, 'lxml')
                items = soup.select('#links .result')
                for item in items:
                    if len(results) >= max_results:
                        break
                    title_tag = item.select_one('.result__a')
                    if not title_tag:
                        continue
                    title = title_tag.get_text(strip=True)
                    raw_href = title_tag.get('href', '')
                    if raw_href.startswith('//'):
                        raw_href = 'https:' + raw_href
                    parsed_href = urlparse(raw_href)
                    qs = parse_qs(parsed_href.query)
                    real_url = unquote(qs['uddg'][0]) if 'uddg' in qs else raw_href
                    snippet_tag = item.select_one('.result__snippet')
                    snippet = snippet_tag.get_text(strip=True) if snippet_tag else ''
                    if real_url.startswith('http'):
                        results.append({'title': title, 'url': real_url, 'snippet': snippet})
                # If we got any results, return immediately.
                if results:
                    return results
                # No results, break to try next endpoint.
                break
            except Exception as exc:
                attempt += 1
                # exponential backoff
                time.sleep(1 * (2 ** attempt))
                if attempt >= max_attempts:
                    # move to next endpoint after max attempts
                    break
    # If all endpoints fail, raise to be caught by caller.
    raise RuntimeError('DuckDuckGo HTML request failed after multiple attempts')
    """Fallback: scrape DuckDuckGo HTML search results with rotating User-Agent."""
    import random
    results = []
    session = requests.Session()
    USER_AGENTS = [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Safari/605.1.15',
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
    ]
    session.headers.update({
        'User-Agent': random.choice(USER_AGENTS),
        'Accept-Language': 'en-US,en;q=0.9',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Referer': 'https://html.duckduckgo.com/',
    })
    ddg_url = 'https://html.duckduckgo.com/html/'
    params = {'q': query, 'kl': 'us-en'}
    try:
        response = session.get(ddg_url, params=params, timeout=15)
        response.raise_for_status()
    except requests.RequestException as exc:
        raise RuntimeError(f"DuckDuckGo HTML request failed: {exc}")
    try:
        soup = BeautifulSoup(response.text, 'lxml')
    except FeatureNotFound:
        soup = BeautifulSoup(response.text, 'html.parser')
    items = soup.select('#links .result')
    for item in items:
        if len(results) >= max_results:
            break
        title_tag = item.select_one('.result__a')
        if not title_tag:
            continue
        title = title_tag.get_text(strip=True)
        raw_href = title_tag.get('href', '')
        if raw_href.startswith('//'):
            raw_href = 'https:' + raw_href
        parsed_href = urlparse(raw_href)
        qs = parse_qs(parsed_href.query)
        if 'uddg' in qs:
            real_url = unquote(qs['uddg'][0])
        else:
            real_url = raw_href
        snippet_tag = item.select_one('.result__snippet')
        snippet = snippet_tag.get_text(strip=True) if snippet_tag else ''
        if real_url and real_url.startswith('http'):
            results.append({'title': title, 'url': real_url, 'snippet': snippet})
    return results

def _ddg_search_via_lite(query, max_results=30):
    """Fallback: use DuckDuckGo Lite HTML interface, lightweight and less likely to be blocked."""
    import random
    results = []
    session = requests.Session()
    USER_AGENTS = [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Safari/605.1.15',
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
    ]
    session.headers.update({
        'User-Agent': random.choice(USER_AGENTS),
        'Accept-Language': 'en-US,en;q=0.9',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    })
    url = 'https://lite.duckduckgo.com/lite/'
    params = {'q': query}
    try:
        response = session.get(url, params=params, timeout=12)
        response.raise_for_status()
    except requests.RequestException as exc:
        raise RuntimeError(f"DuckDuckGo Lite request failed: {exc}")
    try:
        soup = BeautifulSoup(response.text, 'html.parser')
    except Exception:
        soup = BeautifulSoup(response.text, 'html.parser')
    for div in soup.select('div.result'):
        if len(results) >= max_results:
            break
        a_tag = div.select_one('a.result-link')
        if not a_tag:
            continue
        title = a_tag.get_text(strip=True)
        raw_href = a_tag.get('href', '')
        if raw_href.startswith('//'):
            raw_href = 'https:' + raw_href
        results.append({'title': title, 'url': raw_href, 'snippet': ''})
    return results
def _post_filter_results(results, domain, keywords):
    if not domain or not keywords:
        return results
    bare_domain = domain.lower()
    if bare_domain.startswith('www.'):
        bare_domain = bare_domain[4:]
    kw_lower = [kw.lower() for kw in keywords]
    filtered = []
    for r in results:
        url     = r.get('url', '')
        title   = r.get('title', '')
        snippet = r.get('snippet', '')
        try:
            result_netloc = urlparse(url).netloc.lower()
            if result_netloc.startswith('www.'):
                result_netloc = result_netloc[4:]
        except Exception:
            continue
        if result_netloc != bare_domain and not result_netloc.endswith('.' + bare_domain):
            continue
        haystack = (url + ' ' + title + ' ' + snippet).lower()
        if not any(kw in haystack for kw in kw_lower):
            continue
        filtered.append(r)
    return filtered

def _swisscows_search_via_api(query, max_results=30):
    import base64
    results = []
    def rot13_swap(s):
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        res = []
        for c in s:
            if c.lower() in alphabet:
                idx = alphabet.index(c.lower())
                new_idx = (idx + 13) % 26
                shifted = alphabet[new_idx]
                if c.isupper():
                    res.append(shifted.lower())
                else:
                    res.append(shifted.upper())
            else:
                res.append(c)
        return ''.join(res)

    def generate_nonce(length=32):
        import random
        chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'
        return ''.join(random.choice(chars) for _ in range(length))

    def compute_headers(endpoint, query_params):
        nonce = generate_nonce(32)
        rot_nonce = rot13_swap(nonce)
        sorted_keys = sorted(query_params.keys())
        query_parts = []
        for k in sorted_keys:
            query_parts.append(f'{k}={query_params[k]}')
        query_string = '?' + '&'.join(query_parts)
        input_string = endpoint + query_string + rot_nonce
        hash_bytes = hashlib.sha256(input_string.encode('utf-8')).digest()
        base64_str = base64.b64encode(hash_bytes).decode('utf-8')
        signature = base64_str.replace('=', '').replace('+', '-').replace('/', '_')
        return {
            'X-Request-Nonce': nonce,
            'X-Request-Signature': signature
        }

    endpoint = '/v5/web/search'
    query_params = {
        'query': query,
        'offset': '0',
        'itemsCount': str(min(max_results, 10)),
        'locale': 'en-US',
        'freshness': 'All',
        'spellcheck': 'true'
    }
    try:
        headers = compute_headers(endpoint, query_params)
        headers['User-Agent'] = (
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
            'AppleWebKit/537.36 (KHTML, like Gecko) '
            'Chrome/124.0.0.0 Safari/537.36'
        )
        headers['Accept'] = 'application/json, text/plain, */*'
        session = requests.Session()
        r = session.get('https://api.swisscows.com' + endpoint, params=query_params, headers=headers, timeout=15)
        r.raise_for_status()
        payload = r.json().get('payload', '')
        if not payload or '.' not in payload:
            return []
        parts = payload.split('.')
        if len(parts) < 2:
            return []
        padded = parts[1] + '=' * (4 - len(parts[1]) % 4)
        decoded = base64.b64decode(padded.replace('-', '+').replace('_', '/')).decode('utf-8')
        data = json.loads(decoded)
        for item in data.get('items', []):
            title = item.get('name', '')
            url = item.get('url', '')
            snippet = item.get('description', '')
            if snippet:
                snippet = re.sub(r'<[^>]+>', '', snippet)
                snippet = html.unescape(snippet)
            if url and url.startswith('http'):
                results.append({
                    'title': title,
                    'url': url,
                    'snippet': snippet
                })
    except Exception as exc:
        raise RuntimeError(f"Swisscows request failed: {exc}")
    return results

def _yahoo_search_via_html(query, max_results=30):
    results = []
    session = requests.Session()
    session.headers.update({
        'User-Agent': (
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
            'AppleWebKit/537.36 (KHTML, like Gecko) '
            'Chrome/124.0.0.0 Safari/537.36'
        ),
    })
    url = 'https://search.yahoo.com/search'
    params = {'p': query}
    try:
        response = session.get(url, params=params, timeout=15)
        response.raise_for_status()
    except requests.RequestException as exc:
        raise RuntimeError(f"Yahoo HTML request failed: {exc}")
    try:
        soup = BeautifulSoup(response.text, 'lxml')
    except FeatureNotFound:
        soup = BeautifulSoup(response.text, 'html.parser')
    items = soup.select('.algo')
    for item in items:
        if len(results) >= max_results:
            break
        title_tag = item.select_one('.compTitle h3') or item.select_one('.compTitle .title')
        a_tag = item.select_one('.compTitle a') or item.select_one('a')
        snippet_tag = item.select_one('.compText')
        if not title_tag or not a_tag:
            continue
        title = title_tag.get_text(strip=True)
        raw_href = a_tag.get('href', '')
        real_url = raw_href
        if '/RU=' in raw_href:
            m = re.search(r'/RU=([^/]+)', raw_href)
            if m:
                real_url = unquote(m.group(1))
        snippet = snippet_tag.get_text(strip=True) if snippet_tag else ''
        if real_url and real_url.startswith('http'):
            results.append({'title': title, 'url': real_url, 'snippet': snippet})
    return results

def _bing_search_via_html(query, max_results=30):
    """Fallback: scrape Bing HTML search results."""
    results = []
    session = requests.Session()
    session.headers.update({
        'User-Agent': (
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
            'AppleWebKit/537.36 (KHTML, like Gecko) '
            'Chrome/124.0.0.0 Safari/537.36'
        ),
        'Accept-Language': 'en-US,en;q=0.9',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    })
    url = 'https://www.bing.com/search'
    params = {'q': query, 'count': str(min(max_results, 50))}
    try:
        response = session.get(url, params=params, timeout=15)
        response.raise_for_status()
    except requests.RequestException as exc:
        raise RuntimeError(f"Bing HTML request failed: {exc}")
    try:
        soup = BeautifulSoup(response.text, 'lxml')
    except FeatureNotFound:
        soup = BeautifulSoup(response.text, 'html.parser')
    # Bing organic results live in <li class="b_algo">
    items = soup.select('li.b_algo')
    for item in items:
        if len(results) >= max_results:
            break
        a_tag = item.select_one('h2 a')
        if not a_tag:
            continue
        title = a_tag.get_text(strip=True)
        raw_href = a_tag.get('href', '')
        snippet_tag = item.select_one('.b_caption p') or item.select_one('p')
        snippet = snippet_tag.get_text(strip=True) if snippet_tag else ''
        if raw_href and raw_href.startswith('http'):
            results.append({'title': title, 'url': raw_href, 'snippet': snippet})
    return results

def _brave_search_via_html(query, max_results=30):
    """Fallback: scrape Brave Search HTML results. Brave is less aggressive on cloud IPs."""
    results = []
    session = requests.Session()
    session.headers.update({
        'User-Agent': (
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
            'AppleWebKit/537.36 (KHTML, like Gecko) '
            'Chrome/124.0.0.0 Safari/537.36'
        ),
        'Accept-Language': 'en-US,en;q=0.9',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    })
    url = 'https://search.brave.com/search'
    params = {'q': query, 'num': str(min(max_results, 50))}
    try:
        response = session.get(url, params=params, timeout=15)
        response.raise_for_status()
    except requests.RequestException as exc:
        raise RuntimeError(f"Brave HTML request failed: {exc}")
    try:
        soup = BeautifulSoup(response.text, 'lxml')
    except FeatureNotFound:
        soup = BeautifulSoup(response.text, 'html.parser')
    # Brave organic results are in <div class="result"> blocks
    for div in soup.select('div.result'):
        if len(results) >= max_results:
            break
        a_tag = div.select_one('a[data-url]') or div.select_one('a')
        if not a_tag:
            continue
        raw_href = a_tag.get('href', '')
        if not raw_href.startswith('http'):
            continue
        title_tag = div.select_one('h2') or div.select_one('h3')
        title = title_tag.get_text(strip=True) if title_tag else ''
        snippet_tag = div.select_one('p')
        snippet = snippet_tag.get_text(strip=True) if snippet_tag else ''
        results.append({'title': title, 'url': raw_href, 'snippet': snippet})
    return results

def _google_search_via_html(query, max_results=30):
    """Fallback: scrape Google HTML search results (same as before)."""
    results = []
    session = requests.Session()
    # rotate a few common user agents to lower chance of blocking
    USER_AGENTS = [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Safari/605.1.15',
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
    ]
    def _random_user_agent():
        import random
        return random.choice(USER_AGENTS)

    url = 'https://www.google.com/search'
    params = {'q': query, 'num': str(min(max_results, 100)), 'hl': 'en'}
    try:
        response = session.get(url, params=params, timeout=15)
        response.raise_for_status()
    except requests.RequestException as exc:
        raise RuntimeError(f"Google HTML request failed: {exc}")
    try:
        soup = BeautifulSoup(response.text, 'lxml')
    except FeatureNotFound:
        soup = BeautifulSoup(response.text, 'html.parser')
    # Google organic results: try multiple known selectors
    for div in soup.select('div.g, div.tF2Cxc, div.yuRUbf'):
        if len(results) >= max_results:
            break
        a_tag = div.select_one('a[href]')
        if not a_tag:
            continue
        raw_href = a_tag.get('href', '')
        if not raw_href.startswith('http'):
            continue
        # Skip google internal links
        if 'google.com' in raw_href and '/search' in raw_href:
            continue
        title_tag = div.select_one('h3')
        title = title_tag.get_text(strip=True) if title_tag else ''
        snippet_tag = div.select_one('div.VwiC3b, span.aCOpRe, div.IsZvec')
        snippet = snippet_tag.get_text(strip=True) if snippet_tag else ''
        results.append({'title': title, 'url': raw_href, 'snippet': snippet})
    return results

def _searxng_search_via_html(query, max_results=30):
    """Fallback: query a list of public SearXNG instances and aggregate results.
    If an instance fails, it is skipped and the next one is tried.
    """
    instances = [
        'https://searx.be',
        'https://searxng.eu',
        'https://searx.fmac.xyz',
        'https://searx.tiekoetter.com',
        'https://searx.gnous.eu',
    ]
    results = []
    for base in instances:
        try:
            url = f"{base}/search"
            params = {'q': query, 'format': 'json', 'num': str(min(max_results, 30))}
            session = requests.Session()
            session.headers.update({
                'User-Agent': (
                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                    'AppleWebKit/537.36 (KHTML, like Gecko) '
                    'Chrome/124.0.0.0 Safari/537.36'
                ),
                'Accept': 'application/json',
            })
            resp = session.get(url, params=params, timeout=12)
            resp.raise_for_status()
            data = resp.json()
            for item in data.get('results', []):
                if len(results) >= max_results:
                    break
                title = item.get('title', '')
                link = item.get('url', '')
                snippet = item.get('content', '') or item.get('snippet', '')
                if link and link.startswith('http'):
                    results.append({'title': title, 'url': link, 'snippet': snippet})
            if results:
                break  # stop after first successful instance
        except Exception:
            continue  # try next instance silently
    return results
    """Fallback: query a list of public SearXNG instances and aggregate results.
    If an instance fails, it is skipped and the next one is tried.
    """
    instances = [
        'https://searx.be',
        'https://searxng.eu',
        'https://searx.fmac.xyz',
        'https://searx.tiekoetter.com',
        'https://searx.gnous.eu',
    ]
    results = []
    for base in instances:
        try:
            url = f"{base}/search"
            params = {'q': query, 'format': 'json', 'num': str(min(max_results, 30))}
            session = requests.Session()
            session.headers.update({
                'User-Agent': (
                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                    'AppleWebKit/537.36 (KHTML, like Gecko) '
                    'Chrome/124.0.0.0 Safari/537.36'
                ),
                'Accept': 'application/json',
            })
            resp = session.get(url, params=params, timeout=12)
            resp.raise_for_status()
            data = resp.json()
            for item in data.get('results', []):
                if len(results) >= max_results:
                    break
                title = item.get('title', '')
                link = item.get('url', '')
                snippet = item.get('content', '') or item.get('snippet', '')
                if link and link.startswith('http'):
                    results.append({'title': title, 'url': link, 'snippet': snippet})
            if results:
                break  # stop after first successful instance
        except Exception:
            continue  # try next instance silently
    return results

def _startpage_search_via_html(query, max_results=30):
    """Fallback: search via Startpage (privacy proxy to Google)."""
    results = []
    session = requests.Session()
    session.headers.update({
        'User-Agent': (
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
            'AppleWebKit/537.36 (KHTML, like Gecko) '
            'Chrome/124.0.0.0 Safari/537.36'
        ),
        'Accept-Language': 'en-US,en;q=0.9',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    })
    url = 'https://www.startpage.com/do/search'
    params = {'query': query, 'cat': 'web', 'language': 'english'}
    try:
        response = session.get(url, params=params, timeout=15)
        response.raise_for_status()
    except requests.RequestException as exc:
        raise RuntimeError(f"Startpage HTML request failed: {exc}")
    try:
        soup = BeautifulSoup(response.text, 'lxml')
    except FeatureNotFound:
        soup = BeautifulSoup(response.text, 'html.parser')
    for div in soup.select('div.w-gl__result'):  # generic selector used by Startpage
        if len(results) >= max_results:
            break
        a_tag = div.select_one('a')
        if not a_tag:
            continue
        raw_href = a_tag.get('href', '')
        if not raw_href.startswith('http'):
            continue
        title_tag = div.select_one('h3')
        title = title_tag.get_text(strip=True) if title_tag else ''
        snippet_tag = div.select_one('p')
        snippet = snippet_tag.get_text(strip=True) if snippet_tag else ''
        results.append({'title': title, 'url': raw_href, 'snippet': snippet})
    return results

def ddg_find_urls(query, domain='', keywords=None, max_results=20):
    if keywords is None:
        keywords = []
    fetch_count = max(max_results * 4, 60)
    raw_results = []
    method = 'none'
    ddg_error = ''
    # Try library (duckduckgo-search)
    try:
        raw_results = _ddg_search_via_library(query, max_results=fetch_count)
        method = 'library'
    except Exception as e:
        ddg_error = f"Library: {e}"
    # Fallback to HTML scraping with rotating UA
    if not raw_results:
        try:
            raw_results = _ddg_search_via_html(query, max_results=fetch_count)
            if raw_results:
                method = 'html_scrape'
        except Exception as html_err:
            ddg_error += f" | HTML: {html_err}"
    # Final fallback to Lite version
    if not raw_results:
        try:
            raw_results = _ddg_search_via_lite(query, max_results=fetch_count)
            if raw_results:
                method = 'lite_scrape'
        except Exception as lite_err:
            ddg_error += f" | Lite: {lite_err}"
    if not raw_results:
        combined_error = f"DDG failed ({ddg_error})"
        return [], 'none', combined_error
    filtered = _post_filter_results(raw_results, domain, keywords)
    if raw_results and not filtered:
        return raw_results, method, 'NO_KEYWORD_DOMAIN_MATCH'
    return filtered, method, ''