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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
"""
============================================
Core Scraper Engine
- Orchestrates the entire scraping process for ONE novel
- Login โ†’ Navigate โ†’ Scrape Chapter โ†’ Next Chapter โ†’ Repeat
- Handles errors, captchas, and database saves
- Each novel runs as an independent async task
============================================
"""

import asyncio
import logging
import random
import re
from typing import Optional, Dict, Any
from datetime import datetime, timezone
from playwright.async_api import (
    Page,
    TimeoutError as PlaywrightTimeout,
    Error as PlaywrightError,
)
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.exc import IntegrityError

from app.config import settings
from app.scraper.browser_manager import browser_manager
from app.scraper.human_simulator import HumanSimulator
from app.scraper.captcha_detector import captcha_detector
from app.database.connection import get_session_factory
from deep_translator import GoogleTranslator

from app.database.crud import (
    save_chapter,
    update_novel_status,
    increment_chapter_count,
    get_last_chapter_number,
    chapter_exists,
)
from app.database.models import NovelStatus

logger = logging.getLogger(__name__)


# ============================================
# Shared State for UI Status Updates
# ============================================
# This dictionary is read by the API routes to show live status
scraper_status: Dict[int, Dict[str, Any]] = {}


def update_status(novel_id: int, **kwargs):
    """Update the live status for a novel (read by UI)."""
    if novel_id not in scraper_status:
        scraper_status[novel_id] = {}
    scraper_status[novel_id].update(kwargs)
    scraper_status[novel_id]["last_updated"] = datetime.now(timezone.utc).isoformat()


# ============================================
# Login Handlers
# ============================================
async def attempt_login(
    page: Page,
    human: HumanSimulator,
    novel_id: int,
    url: str,
    email: Optional[str],
    password: Optional[str],
) -> bool:
    """
    Attempt to log in to the novel website.
    
    Strategy:
    1. Navigate to the URL
    2. Look for common login form selectors
    3. Fill in credentials
    4. Submit the form
    5. Verify login succeeded
    
    Returns True if login succeeded (or wasn't needed).
    """
    if not email or not password:
        logger.info(f"Novel {novel_id}: No credentials provided, skipping login.")
        return True

    update_status(novel_id, phase="logging_in", message="Attempting login...")

    try:
        # Navigate to the page first
        logger.info(f"Novel {novel_id}: Navigating to {url} for login...")
        await page.goto(url, wait_until="domcontentloaded")
        await human.simulate_page_arrival()

        # --- Common login form selectors (try each one) ---
        login_selectors = [
            # Email/username fields
            {
                "email": [
                    "input[name='email']",
                    "input[type='email']",
                    "input[name='username']",
                    "input[name='log']",
                    "input[id='email']",
                    "input[id='username']",
                    "#login-email",
                    "input[placeholder*='email' i]",
                    "input[placeholder*='username' i]",
                ],
                "password": [
                    "input[name='password']",
                    "input[type='password']",
                    "input[name='pwd']",
                    "input[id='password']",
                    "#login-password",
                ],
                "submit": [
                    "button[type='submit']",
                    "input[type='submit']",
                    "button.login-btn",
                    "button.sign-in",
                    "#login-submit",
                    "button:has-text('Log In')",
                    "button:has-text('Sign In')",
                    "button:has-text('Login')",
                ],
            }
        ]

        # Try to find and fill the login form
        email_filled = False
        password_filled = False
        
        for selector_group in login_selectors:
            # Find email field
            for email_sel in selector_group["email"]:
                try:
                    email_field = await page.query_selector(email_sel)
                    if email_field:
                        await human.type_like_human(email_sel, email)
                        email_filled = True
                        logger.info(f"Novel {novel_id}: Email filled using {email_sel}")
                        break
                except Exception:
                    continue

            # Find password field
            for pass_sel in selector_group["password"]:
                try:
                    pass_field = await page.query_selector(pass_sel)
                    if pass_field:
                        await human.type_like_human(pass_sel, password)
                        password_filled = True
                        logger.info(f"Novel {novel_id}: Password filled using {pass_sel}")
                        break
                except Exception:
                    continue

            if email_filled and password_filled:
                break

        if not email_filled or not password_filled:
            logger.warning(
                f"Novel {novel_id}: Could not find login form fields. "
                f"Email found: {email_filled}, Password found: {password_filled}. "
                f"Proceeding without login."
            )
            return True  # Continue anyway, maybe login isn't needed

        # Submit the form
        await human.medium_delay("before clicking login")
        
        submitted = False
        for selector_group in login_selectors:
            for submit_sel in selector_group["submit"]:
                try:
                    submit_btn = await page.query_selector(submit_sel)
                    if submit_btn:
                        await submit_btn.click()
                        submitted = True
                        logger.info(f"Novel {novel_id}: Login form submitted using {submit_sel}")
                        break
                except Exception:
                    continue
            if submitted:
                break

        if not submitted:
            # Try pressing Enter as fallback
            await page.keyboard.press("Enter")
            logger.info(f"Novel {novel_id}: Login submitted via Enter key")

        # Wait for navigation after login
        await human.long_delay("waiting for login response")

        # Check if login was successful (very basic check)
        page_content = await page.content()
        page_content_lower = page_content.lower()

        login_failed_indicators = [
            "invalid password",
            "incorrect password",
            "login failed",
            "wrong password",
            "invalid credentials",
            "account not found",
            "error logging in",
        ]

        for indicator in login_failed_indicators:
            if indicator in page_content_lower:
                logger.error(f"Novel {novel_id}: Login appears to have failed ('{indicator}' found)")
                update_status(novel_id, phase="login_failed", message=f"Login failed: {indicator}")
                return False

        logger.info(f"Novel {novel_id}: Login appears successful! โœ…")
        update_status(novel_id, phase="logged_in", message="Login successful")
        return True

    except PlaywrightTimeout:
        logger.error(f"Novel {novel_id}: Login page timed out")
        return False
    except Exception as e:
        logger.error(f"Novel {novel_id}: Login error: {e}")
        return False


# ============================================
# Content Extraction
# ============================================
async def extract_chapter_content(
    page: Page,
    novel_id: int,
    content_selector: str,
) -> Optional[Dict[str, str]]:
    """
    Extract clean chapter text from the current page.
    
    Returns:
        {
            "title": "Chapter 123: The Battle",
            "content": "The full chapter text...",
            "url": "https://..."
        }
        or None if extraction failed
    """
    try:
        # --- Try multiple content selectors (comma-separated) ---
        selectors = [s.strip() for s in content_selector.split(",")]
        
        content_element = None
        used_selector = None
        
        for selector in selectors:
            try:
                content_element = await page.query_selector(selector)
                if content_element:
                    used_selector = selector
                    break
            except Exception:
                continue

        if content_element is None:
            logger.warning(f"Novel {novel_id}: No content element found with selectors: {content_selector}")
            return None

        # --- Extract text content ---
        raw_text = await content_element.inner_text()

        if not raw_text or len(raw_text.strip()) < 50:
            logger.warning(f"Novel {novel_id}: Content too short ({len(raw_text.strip())} chars)")
            return None

        # --- Clean the text ---
        clean_text = clean_chapter_text(raw_text)

        # --- Try to get chapter title ---
        title = await extract_chapter_title(page)

        # --- Get current URL ---
        current_url = page.url

        logger.info(
            f"Novel {novel_id}: Extracted chapter "
            f"(title: '{title}', {len(clean_text)} chars, selector: {used_selector})"
        )

        return {
            "title": title,
            "content": clean_text,
            "url": current_url,
        }

    except Exception as e:
        logger.error(f"Novel {novel_id}: Content extraction error: {e}")
        return None


async def extract_chapter_title(page: Page) -> str:
    """
    Try to extract the chapter title from the page.
    Tries multiple common selectors.
    """
    title_selectors = [
        "h1.chapter-title",
        "h1.entry-title",
        ".chapter-title",
        "h1",
        "h2.chapter-title",
        ".text-center h1",
        ".reader-title",
        "#chapter-heading",
        ".chr-title",
        ".title-chapter",
    ]

    for selector in title_selectors:
        try:
            element = await page.query_selector(selector)
            if element:
                title = await element.inner_text()
                title = title.strip()
                if title and len(title) < 200:  # Reasonable title length
                    return title
        except Exception:
            continue

    # Fallback: use page title
    try:
        page_title = await page.title()
        if page_title:
            return page_title.strip()[:200]
    except Exception:
        pass

    return "Untitled Chapter"


def clean_chapter_text(raw_text: str) -> str:
    """
    Clean raw scraped text:
    - Remove excessive whitespace
    - Remove common ad/junk text
    - Normalize line breaks
    """
    if not raw_text:
        return ""

    text = raw_text

    # --- Remove common junk patterns ---
    junk_patterns = [
        r"(?i)translator[:\s]*.*?(?=\n|$)",
        r"(?i)editor[:\s]*.*?(?=\n|$)",
        r"(?i)please read at.*?(?=\n|$)",
        r"(?i)support us at.*?(?=\n|$)",
        r"(?i)read (?:the )?latest (?:chapter )?at.*?(?=\n|$)",
        r"(?i)visit.*?for (?:the )?latest.*?(?=\n|$)",
        r"(?i)if you find any errors.*?(?=\n|$)",
        r"(?i)join our discord.*?(?=\n|$)",
        r"(?i)patreon\.com.*?(?=\n|$)",
        r"(?i)ko-fi\.com.*?(?=\n|$)",
        r"(?i)advertisement",
        r"(?i)sponsored content",
    ]

    for pattern in junk_patterns:
        text = re.sub(pattern, "", text)

    # --- Normalize whitespace ---
    # Replace multiple newlines with double newline (paragraph break)
    text = re.sub(r"\n{3,}", "\n\n", text)
    
    # Replace multiple spaces with single space
    text = re.sub(r" {2,}", " ", text)
    
    # Clean up lines
    lines = text.split("\n")
    cleaned_lines = [line.strip() for line in lines]
    text = "\n".join(cleaned_lines)

    # Remove leading/trailing whitespace
    text = text.strip()

    return text


# ============================================
# Next Chapter Navigation
# ============================================
async def click_next_chapter(
    page: Page,
    human: HumanSimulator,
    novel_id: int,
    next_button_selector: str,
) -> bool:
    """
    Find and click the "Next Chapter" button.
    
    Returns True if navigation succeeded, False if no next chapter found.
    """
    try:
        # --- Try multiple selectors (comma-separated) ---
        selectors = [s.strip() for s in next_button_selector.split(",")]
        
        next_button = None
        used_selector = None

        for selector in selectors:
            try:
                next_button = await page.query_selector(selector)
                if next_button:
                    # Verify it's visible and clickable
                    is_visible = await next_button.is_visible()
                    is_enabled = await next_button.is_enabled()
                    
                    if is_visible and is_enabled:
                        used_selector = selector
                        break
                    else:
                        next_button = None
            except Exception:
                continue

        if next_button is None:
            # --- Fallback: Try text-based search ---
            text_patterns = [
                "Next Chapter",
                "Next",
                "Next โ†’",
                "Next >>",
                "โ†’",
                ">>",
                "Continue Reading",
                "NEXT",
            ]
            
            for pattern in text_patterns:
                try:
                    next_button = await page.query_selector(f"a:has-text('{pattern}')")
                    if next_button:
                        is_visible = await next_button.is_visible()
                        if is_visible:
                            used_selector = f"text='{pattern}'"
                            break
                        next_button = None
                except Exception:
                    continue

        if next_button is None:
            logger.info(f"Novel {novel_id}: No 'Next Chapter' button found. Might be the last chapter.")
            return False

        # --- Get button position for human-like mouse movement ---
        try:
            box = await next_button.bounding_box()
            if box:
                center_x = int(box["x"] + box["width"] / 2)
                center_y = int(box["y"] + box["height"] / 2)
                await human.simulate_before_click(center_x, center_y)
        except Exception:
            pass

        # --- Click the button ---
        current_url = page.url
        
        await next_button.click()
        logger.info(f"Novel {novel_id}: Clicked 'Next Chapter' ({used_selector})")

        # --- Wait for navigation ---
        try:
            await page.wait_for_load_state("domcontentloaded", timeout=20000)
        except PlaywrightTimeout:
            logger.warning(f"Novel {novel_id}: Page load timeout after clicking next")

        # --- Verify we actually navigated ---
        new_url = page.url
        if new_url == current_url:
            # Sometimes click doesn't navigate, maybe it opens in same page via AJAX
            await asyncio.sleep(3)
            new_url = page.url
            
            if new_url == current_url:
                logger.warning(f"Novel {novel_id}: URL didn't change after clicking next")
                # Still might have loaded content via AJAX, so continue

        # --- Human delay after navigation ---
        await human.simulate_page_arrival()

        return True

    except PlaywrightTimeout:
        logger.warning(f"Novel {novel_id}: Timeout while clicking next chapter")
        return False
    except Exception as e:
        logger.error(f"Novel {novel_id}: Error clicking next chapter: {e}")
        return False


# ============================================
# Main Scraping Loop (ONE Novel)
# ============================================


# ============================================
# Helper: Translate to Hindi (Google Translate)
# ============================================
def _translate_hindi(text: str) -> str:
    """Translate English text to Hindi in chunks."""
    try:
        translator = GoogleTranslator(source='en', target='hi')
        chunk_size = 4000
        if len(text) <= chunk_size:
            return translator.translate(text) or text
        
        chunks, current = [], ""
        for word in text.split(' '):
            if len(current) + len(word) + 1 <= chunk_size:
                current += (" " + word) if current else word
            else:
                if current:
                    chunks.append(translator.translate(current) or current)
                current = word
        if current:
            chunks.append(translator.translate(current) or current)
        return " ".join(chunks)
    except Exception as e:
        logger.warning(f"Translation failed: {e} โ€” saving English only")
        return ""

async def scrape_novel(novel_id: int, novel_data: Dict[str, Any]):
    """
    Main scraping function for a single novel.
    This runs as an independent async task.
    
    Flow:
    1. Acquire semaphore slot
    2. Create browser context
    3. Login (if credentials provided)
    4. Navigate to starting URL
    5. Loop:
       a. Check for captcha/protection
       b. Extract chapter content
       c. Save to database
       d. Click next chapter
       e. Repeat
    6. Clean up browser context
    """
    url = novel_data["url"]
    title = novel_data.get("title", "Unknown Novel")
    email = novel_data.get("login_email")
    password = novel_data.get("login_password")
    next_btn_selector = novel_data.get(
        "next_button_selector",
        "a.next_page, a[rel='next'], .next-chap, button.next-chapter"
    )
    content_sel = novel_data.get(
        "content_selector",
        ".chapter-content, .reading-content, #chapter-content, .text-left"
    )

    update_status(
        novel_id,
        title=title,
        phase="queued",
        message="Waiting for available browser slot...",
        chapters_scraped=0,
        current_url=url,
    )

    # --- Step 1: Acquire semaphore (wait for available slot) ---
    logger.info(f"Novel {novel_id} ({title}): Waiting for browser slot...")
    
    async with browser_manager.semaphore:
        logger.info(f"Novel {novel_id} ({title}): ๐ŸŸข Got browser slot! Starting...")
        
        context = None
        page = None
        session_factory = get_session_factory()
        
        try:
            # --- Step 2: Create browser context ---
            update_status(novel_id, phase="initializing", message="Creating browser...")
            context, page = await browser_manager.create_context_for_novel(novel_id)
            human = HumanSimulator(page)

            # --- Step 3: Update DB status ---
            async with session_factory() as db:
                await update_novel_status(
                    db, novel_id, NovelStatus.LOGGING_IN,
                    current_url=url,
                )
                await db.commit()

            # --- Step 4: Login ---
            login_success = await attempt_login(
                page, human, novel_id, url, email, password
            )
            
            if not login_success:
                async with session_factory() as db:
                    await update_novel_status(
                        db, novel_id, NovelStatus.FAILED,
                        error_message="Login failed",
                    )
                    await db.commit()
                update_status(novel_id, phase="failed", message="Login failed!")
                return

            # --- Step 5: Navigate to starting URL ---
            update_status(novel_id, phase="navigating", message=f"Going to {url}")
            
            logger.info(f"Novel {novel_id}: Navigating to starting URL: {url}")
            await page.goto(url, wait_until="domcontentloaded")
            await human.simulate_page_arrival()

            async with session_factory() as db:
                await update_novel_status(
                    db, novel_id, NovelStatus.SCRAPING,
                    current_url=url,
                )
                await db.commit()

            # --- Step 6: Get last scraped chapter number (for resume) ---
            async with session_factory() as db:
                chapter_number = await get_last_chapter_number(db, novel_id)
            
            chapter_number += 1  # Start from next chapter
            consecutive_failures = 0
            max_consecutive_failures = 5

            # --- Step 7: MAIN SCRAPING LOOP ---
            logger.info(f"Novel {novel_id}: Starting scraping loop from chapter {chapter_number}")
            
            while True:
                update_status(
                    novel_id,
                    phase="scraping",
                    message=f"Processing chapter {chapter_number}...",
                    current_url=page.url,
                    chapters_scraped=chapter_number - 1,
                )

                # --- 7a: Check for captcha/protection ---
                is_blocked, block_reason = await captcha_detector.check_for_protection(
                    page, novel_id, content_sel
                )

                if is_blocked:
                    # First, try waiting for auto-resolution (Cloudflare)
                    if "cloudflare" in block_reason.lower():
                        auto_resolved = await captcha_detector.wait_for_cloudflare_auto_resolve(
                            page, novel_id, max_wait=15
                        )
                        if auto_resolved:
                            is_blocked = False

                if is_blocked:
                    # --- Need manual intervention ---
                    update_status(
                        novel_id,
                        phase="captcha_detected",
                        message=f"โš ๏ธ Protection detected: {block_reason}",
                    )

                    # Take screenshot and notify
                    screenshot_file = await captcha_detector.handle_protection_detected(
                        page, novel_id, block_reason, browser_manager
                    )

                    # Update DB
                    async with session_factory() as db:
                        await update_novel_status(
                            db, novel_id, NovelStatus.PAUSED_CAPTCHA,
                            error_message=block_reason,
                            screenshot_path=screenshot_file,
                            needs_intervention=True,
                        )
                        await db.commit()

                    update_status(
                        novel_id,
                        phase="waiting_intervention",
                        message="Waiting for you to solve the captcha...",
                        screenshot=screenshot_file,
                    )

                    # Wait for user to solve it
                    intervention_success = await captcha_detector.wait_for_intervention(
                        novel_id, timeout_minutes=30
                    )

                    if not intervention_success:
                        logger.error(f"Novel {novel_id}: Intervention timeout, stopping.")
                        async with session_factory() as db:
                            await update_novel_status(
                                db, novel_id, NovelStatus.FAILED,
                                error_message="Captcha intervention timeout",
                            )
                            await db.commit()
                        update_status(novel_id, phase="failed", message="Captcha timeout!")
                        return

                    # Intervention completed, clear the flag
                    async with session_factory() as db:
                        await update_novel_status(
                            db, novel_id, NovelStatus.SCRAPING,
                            needs_intervention=False,
                        )
                        await db.commit()

                    # Wait a moment and re-check
                    await human.medium_delay("post-intervention")
                    continue  # Re-check the page

                # --- 7b: Extract chapter content ---
                chapter_data = await extract_chapter_content(
                    page, novel_id, content_sel
                )

                if chapter_data is None:
                    consecutive_failures += 1
                    logger.warning(
                        f"Novel {novel_id}: Failed to extract chapter {chapter_number} "
                        f"(failure {consecutive_failures}/{max_consecutive_failures})"
                    )
                    
                    if consecutive_failures >= max_consecutive_failures:
                        logger.error(
                            f"Novel {novel_id}: Too many consecutive failures, stopping."
                        )
                        async with session_factory() as db:
                            await update_novel_status(
                                db, novel_id, NovelStatus.FAILED,
                                error_message=f"Too many extraction failures at chapter {chapter_number}",
                            )
                            await db.commit()
                        update_status(
                            novel_id, phase="failed",
                            message=f"Failed after {max_consecutive_failures} consecutive extraction failures"
                        )
                        return
                    
                    # Try clicking next anyway
                    has_next = await click_next_chapter(
                        page, human, novel_id, next_btn_selector
                    )
                    if not has_next:
                        break
                    continue

                # Reset failure counter on success
                consecutive_failures = 0

                # --- 7c: Save to database ---
                try:
                    async with session_factory() as db:
                        # Check if already saved (for resume scenarios)
                        already_exists = await chapter_exists(
                            db, novel_id, chapter_number
                        )
                        
                        if not already_exists:
                            # --- Translate to Hindi in background thread ---
                            loop = asyncio.get_event_loop()
                            hindi_content = await loop.run_in_executor(
                                None, _translate_hindi, chapter_data["content"]
                            )
                            hindi_title = await loop.run_in_executor(
                                None, _translate_hindi, chapter_data["title"]
                            )
                            logger.info(
                                f"Novel {novel_id}: ๐Ÿ‡ฎ๐Ÿ‡ณ Translated Ch {chapter_number} to Hindi"
                            )

                            await save_chapter(
                                db,
                                novel_id=novel_id,
                                chapter_number=chapter_number,
                                content=chapter_data["content"],
                                title=chapter_data["title"],
                                url=chapter_data["url"],
                                content_hindi=hindi_content or None,
                                title_hindi=hindi_title or None,
                            )
                            await increment_chapter_count(db, novel_id)
                            await db.commit()
                            
                            logger.info(
                                f"Novel {novel_id}: โœ… Saved Chapter {chapter_number} "
                                f"- '{chapter_data['title']}'"
                            )
                        else:
                            logger.info(
                                f"Novel {novel_id}: Chapter {chapter_number} already exists, skipping save"
                            )

                except IntegrityError:
                    logger.warning(
                        f"Novel {novel_id}: Chapter {chapter_number} duplicate, skipping"
                    )
                except Exception as e:
                    logger.error(
                        f"Novel {novel_id}: Database error saving chapter {chapter_number}: {e}"
                    )
                    # Don't stop scraping for DB errors, log and continue

                update_status(
                    novel_id,
                    phase="scraping",
                    message=f"โœ… Chapter {chapter_number} saved! Moving to next...",
                    chapters_scraped=chapter_number,
                    last_chapter_title=chapter_data["title"],
                )

                # --- 7d: Human-like reading delay ---
                await human.simulate_reading_chapter()

                # --- 7e: Click Next Chapter ---
                has_next = await click_next_chapter(
                    page, human, novel_id, next_btn_selector
                )

                if not has_next:
                    logger.info(
                        f"Novel {novel_id}: No next chapter found after chapter {chapter_number}. "
                        f"Novel might be complete! ๐ŸŽ‰"
                    )
                    break

                chapter_number += 1

                # --- Safety: Don't scrape more than 10000 chapters ---
                if chapter_number > 10000:
                    logger.warning(f"Novel {novel_id}: Hit 10000 chapter limit, stopping")
                    break

            # --- Step 8: Scraping Complete ---
            async with session_factory() as db:
                await update_novel_status(
                    db, novel_id, NovelStatus.COMPLETED,
                )
                await db.commit()

            update_status(
                novel_id,
                phase="completed",
                message=f"๐ŸŽ‰ Completed! {chapter_number - 1} chapters scraped.",
                chapters_scraped=chapter_number - 1,
            )
            logger.info(
                f"Novel {novel_id} ({title}): ๐ŸŽ‰ COMPLETED! "
                f"{chapter_number - 1} chapters scraped."
            )

        except PlaywrightError as e:
            error_msg = f"Browser error: {str(e)}"
            logger.error(f"Novel {novel_id}: {error_msg}")
            
            async with session_factory() as db:
                await update_novel_status(
                    db, novel_id, NovelStatus.PAUSED_ERROR,
                    error_message=error_msg,
                )
                await db.commit()
            
            update_status(novel_id, phase="error", message=error_msg)

        except Exception as e:
            error_msg = f"Unexpected error: {str(e)}"
            logger.error(f"Novel {novel_id}: {error_msg}", exc_info=True)
            
            try:
                async with session_factory() as db:
                    await update_novel_status(
                        db, novel_id, NovelStatus.PAUSED_ERROR,
                        error_message=error_msg,
                    )
                    await db.commit()
            except Exception:
                pass
            
            update_status(novel_id, phase="error", message=error_msg)

        finally:
            # --- Always clean up the browser context ---
            await browser_manager.close_context(novel_id)
            captcha_detector.clear_intervention(novel_id)
            logger.info(f"Novel {novel_id}: Browser context cleaned up.")


# ============================================
# Task Manager (Start Multiple Novels)
# ============================================
# Store active tasks: {novel_id: asyncio.Task}
active_tasks: Dict[int, asyncio.Task] = {}


async def start_scraping_novel(novel_id: int, novel_data: Dict[str, Any]):
    """
    Start scraping a novel as a background task.
    """
    if novel_id in active_tasks:
        task = active_tasks[novel_id]
        if not task.done():
            logger.warning(f"Novel {novel_id}: Already scraping, ignoring duplicate start")
            return False

    # Create and store the task
    task = asyncio.create_task(
        scrape_novel(novel_id, novel_data),
        name=f"scraper-novel-{novel_id}",
    )
    active_tasks[novel_id] = task

    # Add callback to clean up when done
    def task_done_callback(t: asyncio.Task):
        try:
            exception = t.exception()
            if exception:
                logger.error(
                    f"Novel {novel_id} task failed with exception: {exception}"
                )
        except asyncio.CancelledError:
            logger.info(f"Novel {novel_id} task was cancelled")

    task.add_done_callback(task_done_callback)

    logger.info(f"Novel {novel_id}: Scraping task started! ๐Ÿš€")
    return True


async def stop_scraping_novel(novel_id: int) -> bool:
    """
    Stop scraping a specific novel.
    """
    if novel_id in active_tasks:
        task = active_tasks[novel_id]
        if not task.done():
            task.cancel()
            try:
                await task
            except asyncio.CancelledError:
                pass
            
            # Clean up browser
            await browser_manager.close_context(novel_id)
            
            logger.info(f"Novel {novel_id}: Scraping stopped โœ‹")
            
            update_status(novel_id, phase="stopped", message="Scraping stopped by user")
            return True

    return False


async def stop_all_scraping():
    """Stop all active scraping tasks."""
    for novel_id in list(active_tasks.keys()):
        await stop_scraping_novel(novel_id)
    logger.info("All scraping tasks stopped.")


def get_active_task_ids() -> list:
    """Get IDs of all novels currently being scraped."""
    return [nid for nid, task in active_tasks.items() if not task.done()]