import cloudscraper
import requests
from bs4 import BeautifulSoup
import json
import re
import time
import random
import logging
from typing import Optional, List, Dict, Any
from urllib.parse import quote

logger = logging.getLogger(__name__)

class KomikuScraper:
    """Scraper untuk mengambil data dari Komiku.org"""
    
    def __init__(self):
        self.base_url = "https://komiku.org"
        self.api_url = "https://api.komiku.org"
        self.image_base = "https://img.komiku.org"
        
        # Session untuk API (requests biasa)
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'id,en-US;q=0.9,en;q=0.8',
            'Referer': 'https://komiku.org/',
            'X-Requested-With': 'XMLHttpRequest'
        })
        
        # Cloudscraper untuk chapter (bypass Cloudflare)
        self.scraper = cloudscraper.create_scraper(
            browser={
                'browser': 'chrome',
                'platform': 'windows',
                'desktop': True,
                'mobile': False
            }
        )
        self.scraper.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
            'Accept-Language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7',
            'Referer': 'https://komiku.org/',
        })
    
    def get_html_api(self, url: str, retry_count: int = 3) -> Optional[str]:
        """Get HTML menggunakan requests (untuk API)"""
        for attempt in range(retry_count):
            try:
                logger.info(f"[API] Fetching: {url} (attempt {attempt+1})")
                response = self.session.get(url, timeout=30)
                response.raise_for_status()
                return response.text
            except Exception as e:
                logger.warning(f"Attempt {attempt + 1} failed: {e}")
                if attempt < retry_count - 1:
                    time.sleep(1)
                else:
                    logger.error(f"All attempts failed for {url}")
                    return None
    
    def get_html_chapter(self, url: str, retry_count: int = 3) -> Optional[str]:
        """Get HTML menggunakan cloudscraper (untuk chapter)"""
        for attempt in range(retry_count):
            try:
                logger.info(f"[CHAPTER] Fetching: {url} (attempt {attempt+1})")
                response = self.scraper.get(url, timeout=30)
                
                if "You have been blocked" in response.text or "Cloudflare" in response.text:
                    logger.warning("Blocked by Cloudflare, retrying...")
                    time.sleep(random.uniform(3, 6))
                    continue
                
                return response.text
            except Exception as e:
                logger.error(f"Error: {str(e)}")
                if attempt < retry_count - 1:
                    time.sleep(random.uniform(2, 5))
                else:
                    return None
    
    def _get_image_url(self, img_element) -> str:
        """Extract image URL from img element"""
        if not img_element:
            return ''
        src = img_element.get('data-src', '')
        if src and 'lazy.jpg' not in src:
            return src
        src = img_element.get('src', '')
        if src and 'lazy.jpg' not in src:
            return src
        return ''
    
    def _extract_json_data(self, soup: BeautifulSoup, data_name: str) -> Dict:
        """Extract JSON data from script tags"""
        scripts = soup.find_all('script')
        for script in scripts:
            if script.string and data_name in script.string:
                match = re.search(rf'{data_name}\s*=\s*([{{][^;]+[}}])', script.string)
                if match:
                    try:
                        return json.loads(match.group(1))
                    except:
                        pass
        return {}
    
    def _parse_comic_items(self, soup: BeautifulSoup, include_chapters: bool = True) -> List[Dict[str, Any]]:
        """Parse items dari berbagai halaman (pustaka, genre, search)"""
        results = []
        items = soup.find_all('div', class_='bge')
        
        for item in items:
            try:
                img_wrap = item.find('div', class_='bgei')
                if not img_wrap:
                    continue
                
                link = img_wrap.find('a')
                if not link:
                    continue
                
                comic_url = link.get('href', '')
                slug = comic_url.replace('/manga/', '').rstrip('/') if comic_url else ''
                
                img = link.find('img')
                image_url = self._get_image_url(img)
                
                type_info = img_wrap.find('div', class_='tpe1_inf')
                comic_type = ''
                genre = ''
                if type_info:
                    type_text = type_info.get_text(strip=True)
                    parts = type_text.split()
                    if parts:
                        comic_type = parts[0].strip()
                        if len(parts) > 1:
                            genre = ' '.join(parts[1:]).strip()
                
                rank_span = img_wrap.find('span', class_='up')
                rank = rank_span.get_text(strip=True) if rank_span else None
                
                info_div = item.find('div', class_='kan')
                if not info_div:
                    continue
                
                title_elem = info_div.find('h3')
                title = title_elem.get_text(strip=True) if title_elem else ''
                
                if not title:
                    continue
                
                judul2 = info_div.find('span', class_='judul2')
                readers = ''
                time_ago = ''
                if judul2:
                    judul2_text = judul2.get_text(strip=True)
                    readers_match = re.search(r'([\d.]+[rb]?)', judul2_text)
                    if readers_match:
                        readers = readers_match.group(1)
                    time_match = re.search(r'(\d+\s*(?:menit|jam|hari|minggu|bulan|tahun)\s+lalu)', judul2_text)
                    if time_match:
                        time_ago = time_match.group(1)
                
                desc_p = info_div.find('p')
                description = desc_p.get_text(strip=True) if desc_p else ''
                
                result = {
                    'title': title,
                    'slug': slug,
                    'href': comic_url,
                    'thumbnail': image_url,
                    'type': comic_type,
                    'genre': genre,
                    'rank': rank,
                    'readers': readers,
                    'time_ago': time_ago,
                    'description': description
                }
                
                if include_chapters:
                    first_chapter = None
                    latest_chapter = None
                    
                    chapter_links = info_div.find_all('div', class_='new1')
                    for chap_div in chapter_links:
                        chap_link = chap_div.find('a')
                        if not chap_link:
                            continue
                        
                        chap_url = chap_link.get('href', '')
                        chap_text = chap_link.get_text(strip=True)
                        
                        label_span = chap_div.find('span')
                        if label_span:
                            label = label_span.get_text(strip=True)
                            if 'Awal' in label:
                                first_chapter = {
                                    'chapter': chap_text,
                                    'url': chap_url
                                }
                            elif 'Terbaru' in label:
                                latest_chapter = {
                                    'chapter': chap_text,
                                    'url': chap_url
                                }
                    
                    result['first_chapter'] = first_chapter
                    result['latest_chapter'] = latest_chapter
                
                results.append(result)
                
            except Exception as e:
                logger.warning(f"Error extracting result: {e}")
                continue
        
        return results
    
    def _has_next_page(self, soup: BeautifulSoup) -> bool:
        """Check if there is a next page"""
        next_span = soup.find('span', {'hx-get': re.compile(r'/manga/page/\d+/')})
        if next_span:
            return True
        
        next_link = soup.find('a', string=re.compile(r'Next|Berikutnya|Ã¢â‚¬Âº'))
        if next_link and next_link.get('href'):
            return True
        
        return False
    
    # ==================== PUSTAKA METHODS ====================
    
    def get_pustaka(self, tipe: str = "manga", page: int = 1, orderby: str = None, sorttime: str = None) -> Dict[str, Any]:
        """Get comics from pustaka"""
        if page == 1:
            api_url = f"{self.api_url}/manga/?tipe={tipe}"
        else:
            api_url = f"{self.api_url}/manga/page/{page}/?tipe={tipe}"
        
        if orderby:
            api_url += f"&orderby={orderby}"
        if sorttime:
            api_url += f"&sorttime={sorttime}"
        
        html_content = self.get_html_api(api_url)
        
        if not html_content:
            return {
                'status': False,
                'message': 'Gagal mengambil data dari API',
                'tipe': tipe,
                'page': page,
                'total': 0,
                'data': []
            }
        
        soup = BeautifulSoup(html_content, 'html.parser')
        results = self._parse_comic_items(soup)
        has_next = self._has_next_page(soup)
        
        return {
            'status': True,
            'message': 'Berhasil mendapatkan data',
            'tipe': tipe,
            'page': page,
            'has_next': has_next,
            'total': len(results),
            'data': results
        }
    
    # ==================== SEARCH METHODS ====================
    
    def search_comics(self, query: str) -> Dict[str, Any]:
        """Search comics - SAMA PERSIS KAYAK CODE ASLI"""
        # Coba via API dulu
        api_url = f"{self.api_url}/?post_type=manga&s={query}"
        html_content = self.get_html_api(api_url)
        
        if html_content:
            soup = BeautifulSoup(html_content, 'html.parser')
            results = self._parse_search_results(soup)
            
            if results:
                return {
                    'status': True,
                    'creator': 'Zyann',
                    'message': 'Berhasil mendapatkan hasil pencarian',
                    'q': query,
                    'url': f"{self.base_url}/?s={query}&post_type=manga",
                    'total': len(results),
                    'data': results
                }
        
        # Fallback ke URL utama
        search_url = f"{self.base_url}/?post_type=manga&s={query}"
        html_content = self.get_html_api(search_url)
        
        if not html_content:
            return {
                'status': False,
                'creator': 'Zyann',
                'message': 'Gagal mengambil halaman pencarian',
                'q': query,
                'url': search_url,
                'total': 0,
                'data': []
            }
        
        soup = BeautifulSoup(html_content, 'html.parser')
        results = self._parse_search_results(soup)
        
        return {
            'status': True if results else False,
            'creator': 'Zyann',
            'message': 'Berhasil mendapatkan hasil pencarian' if results else 'Tidak ada hasil ditemukan',
            'q': query,
            'url': search_url,
            'total': len(results),
            'data': results
        }
    
    def _parse_search_results(self, soup: BeautifulSoup) -> List[Dict[str, Any]]:
        """Parse search results - SAMA PERSIS KAYAK CODE ASLI"""
        results = []
        items = soup.find_all('div', class_='bge')
        
        for idx, item in enumerate(items, 1):
            try:
                img_wrap = item.find('div', class_='bgei')
                if not img_wrap:
                    continue
                
                link = img_wrap.find('a')
                if not link:
                    continue
                
                comic_url = link.get('href', '')
                slug = comic_url.replace('/manga/', '').rstrip('/') if comic_url else ''
                
                img = link.find('img')
                image_url = self._get_image_url(img)
                
                type_info = img_wrap.find('div', class_='tpe1_inf')
                comic_type = ''
                genre = ''
                if type_info:
                    type_text = type_info.get_text(strip=True)
                    parts = type_text.split()
                    if parts:
                        comic_type = parts[0].strip()
                        if len(parts) > 1:
                            genre = ' '.join(parts[1:]).strip()
                
                info_div = item.find('div', class_='kan')
                if not info_div:
                    continue
                
                title_elem = info_div.find('h3')
                title = title_elem.get_text(strip=True) if title_elem else ''
                if not title:
                    continue
                
                update_p = info_div.find('p')
                description = update_p.get_text(strip=True) if update_p else ''
                
                first_chapter = None
                latest_chapter = None
                
                chapter_links = info_div.find_all('div', class_='new1')
                for chap_div in chapter_links:
                    chap_link = chap_div.find('a')
                    if not chap_link:
                        continue
                    
                    chap_url = chap_link.get('href', '')
                    chap_text = chap_link.get_text(strip=True)
                    
                    label_span = chap_div.find('span')
                    if label_span:
                        label = label_span.get_text(strip=True)
                        if 'Awal' in label:
                            first_chapter = {
                                'chapter': chap_text,
                                'url': chap_url
                            }
                        elif 'Terbaru' in label:
                            latest_chapter = {
                                'chapter': chap_text,
                                'url': chap_url
                            }
                
                results.append({
                    'no': idx,
                    'title': title,
                    'altTitle': None,
                    'slug': slug,
                    'href': comic_url,
                    'thumbnail': image_url,
                    'type': comic_type,
                    'genre': genre,
                    'description': description,
                    'first_chapter': first_chapter,
                    'latest_chapter': latest_chapter
                })
                
            except Exception as e:
                continue
        
        return results
    
    # ==================== GENRE METHODS ====================
    
    def get_genres(self) -> List[Dict[str, Any]]:
        """Get all genres"""
        html_content = self.get_html_api(f"{self.base_url}/pustaka/")
        if not html_content:
            return []
        
        soup = BeautifulSoup(html_content, 'html.parser')
        genres = []
        seen = set()
        
        genre_selects = soup.find_all('select', {'name': ['genre', 'genre2']})
        
        for select in genre_selects:
            options = select.find_all('option')
            for option in options:
                value = option.get('value', '')
                if not value:
                    continue
                
                text = option.get_text(strip=True)
                match = re.search(r'^(.*?)\s*\(([\d.]+)\)$', text)
                
                if match:
                    name = match.group(1).strip()
                    count = match.group(2).strip()
                else:
                    name = text.strip()
                    count = '0'
                
                slug = value
                key = f"{slug}"
                if key in seen:
                    continue
                seen.add(key)
                
                genres.append({
                    'slug': slug,
                    'name': name,
                    'count': count,
                    'url': f"{self.base_url}/genre/{slug}/"
                })
        
        return genres
    
    def get_genre_comics(self, genre_slug: str, page: int = 1, orderby: str = 'modified', tipe: str = None) -> Dict[str, Any]:
        """Get comics by genre"""
        if page == 1:
            api_url = f"{self.api_url}/genre/{genre_slug}/"
        else:
            api_url = f"{self.api_url}/genre/{genre_slug}/page/{page}/"
        
        if orderby:
            api_url += f"?orderby={orderby}"
        if tipe:
            if '?' in api_url:
                api_url += f"&tipe={tipe}"
            else:
                api_url += f"?tipe={tipe}"
        
        html_content = self.get_html_api(api_url)
        if not html_content:
            return {'status': False, 'message': 'Gagal mengambil data', 'genre': genre_slug, 'page': page, 'total': 0, 'has_next': False, 'data': []}
        
        soup = BeautifulSoup(html_content, 'html.parser')
        results = self._parse_comic_items(soup)
        has_next = self._has_next_page(soup)
        
        return {
            'status': True,
            'message': 'Berhasil mendapatkan data',
            'genre': genre_slug,
            'page': page,
            'has_next': has_next,
            'total': len(results),
            'data': results
        }
    
    # ==================== DETAIL METHODS ====================
    
    def get_manga_detail(self, slug: str) -> Dict[str, Any]:
        """Get detailed information about a manga by slug"""
        manga_url = f"{self.base_url}/manga/{slug}/"
        html_content = self.get_html_api(manga_url)
        
        if not html_content:
            return {
                'status': False,
                'message': 'Gagal mengambil halaman manga',
                'data': {}
            }
        
        soup = BeautifulSoup(html_content, 'html.parser')
        
        # Extract manga data from script
        manga_data = {}
        scripts = soup.find_all('script')
        for script in scripts:
            if script.string and 'mangaData' in script.string:
                match = re.search(r'mangaData\s*=\s*({[^;]+})', script.string)
                if match:
                    try:
                        manga_data = json.loads(match.group(1))
                        break
                    except:
                        pass
        
        detail = {
            'id': manga_data.get('id'),
            'title': '',
            'alt_title': '',
            'cover': '',
            'cover_horizontal': manga_data.get('cover', ''),
            'type': '',
            'status': '',
            'rating': '',
            'genres': [],
            'author': '',
            'views': '',
            'synopsis': '',
            'first_chapter': None,
            'latest_chapter': None,
            'chapters': [],
            'chapters_count': 0
        }
        
        # Title
        title_elem = soup.find('h1')
        if title_elem:
            title_text = title_elem.get_text(strip=True)
            if 'Komik' in title_text:
                title_text = title_text.replace('Komik', '').strip()
            detail['title'] = title_text
        
        # Alt title
        alt_title_span = soup.find('span', class_='j2')
        if alt_title_span:
            detail['alt_title'] = alt_title_span.get_text(strip=True)
        
        # Cover
        cover_img = soup.find('img', {'alt': re.compile(r'Komik.*Bahasa Indonesia')})
        if cover_img:
            detail['cover'] = self._get_image_url(cover_img)
        
        # Info table
        info_table = soup.find('table', class_='inftable')
        if info_table:
            rows = info_table.find_all('tr')
            for row in rows:
                tds = row.find_all('td')
                if len(tds) >= 2:
                    label = tds[0].get_text(strip=True).replace(':', '')
                    value = tds[1]
                    
                    if 'Judul' in label:
                        if not detail['title']:
                            detail['title'] = value.get_text(strip=True)
                    elif 'Judul Alternatif' in label:
                        detail['alt_title'] = value.get_text(strip=True)
                    elif 'Tipe' in label:
                        detail['type'] = value.get_text(strip=True)
                    elif 'Genre' in label:
                        genre_links = value.find_all('a')
                        detail['genres'] = [g.get_text(strip=True) for g in genre_links]
                    elif 'Author' in label:
                        detail['author'] = value.get_text(strip=True)
                    elif 'Status' in label:
                        detail['status'] = value.get_text(strip=True)
                    elif 'Rating' in label:
                        detail['rating'] = value.get_text(strip=True)
                    elif 'Pembaca' in label:
                        detail['views'] = value.get_text(strip=True)
        
        # Synopsis
        synopsis_p = soup.find('p', class_='desc')
        if synopsis_p:
            detail['synopsis'] = synopsis_p.get_text(strip=True)
        
        # First chapter
        first_link = soup.find('a', href=re.compile(r'.*-chapter-01/'))
        if first_link:
            detail['first_chapter'] = {
                'chapter': first_link.get_text(strip=True),
                'url': first_link.get('href', '')
            }
        
        # Latest chapter
        latest_link = soup.find('a', href=re.compile(r'.*-chapter-\d+/'), title=re.compile(r'Terbaru'))
        if not latest_link:
            all_chapter_links = soup.find_all('a', href=re.compile(r'.*-chapter-\d+/'))
            if all_chapter_links:
                latest_link = all_chapter_links[-1]
        
        if latest_link:
            detail['latest_chapter'] = {
                'chapter': latest_link.get_text(strip=True),
                'url': latest_link.get('href', '')
            }
        
        # Chapters list
        chapter_table = soup.find('table', id='Daftar_Chapter')
        if chapter_table:
            tbody = chapter_table.find('tbody')
            if tbody:
                rows = tbody.find_all('tr')
                for row in rows:
                    tds = row.find_all('td')
                    if len(tds) >= 2:
                        if row.find('th'):
                            continue
                        
                        link = row.find('a')
                        if link:
                            chapter_url = link.get('href', '')
                            chapter_text = link.get_text(strip=True)
                            date_td = tds[1] if len(tds) > 1 else None
                            date_text = date_td.get_text(strip=True) if date_td else ''
                            
                            detail['chapters'].append({
                                'chapter': chapter_text,
                                'url': chapter_url,
                                'date': date_text
                            })
            
            detail['chapters_count'] = len(detail['chapters'])
        
        return {
            'status': True,
            'message': 'Berhasil mendapatkan detail manga',
            'data': detail
        }
    
    # ==================== CHAPTER METHODS ====================
    
    def get_chapter_data(self, chapter_slug: str) -> Dict[str, Any]:
        """Get chapter data with images"""
        chapter_url = f"{self.base_url}/{chapter_slug}/"
        html_content = self.get_html_chapter(chapter_url)
        
        if not html_content:
            return {}
        
        soup = BeautifulSoup(html_content, 'html.parser')
        
        # Extract chapter data
        chapter_data = self._extract_json_data(soup, 'chapterData')
        
        # Get images
        images = []
        image_container = soup.find('div', id='Baca_Komik')
        if image_container:
            imgs = image_container.find_all('img')
            for img in imgs:
                src = self._get_image_url(img)
                if src:
                    images.append(src)
        
        if not images and chapter_data.get('gambar'):
            images = chapter_data.get('gambar', [])
        
        # Navigation
        navigation = {}
        prev_link = soup.find('a', {'aria-label': 'Prev'})
        if prev_link and prev_link.get('href'):
            prev_url = prev_link.get('href')
            navigation['previousChapter'] = prev_url.strip('/').split('/')[-1]
        
        next_link = soup.find('a', {'aria-label': 'Next'})
        if next_link and next_link.get('href'):
            next_url = next_link.get('href')
            navigation['nextChapter'] = next_url.strip('/').split('/')[-1]
        
        # Manga title
        manga_title = ''
        title_elem = soup.find('h1')
        if title_elem:
            manga_title = title_elem.get_text(strip=True)
            if 'Komik' in manga_title:
                manga_title = manga_title.replace('Komik', '').strip()
        
        result = {
            'manga_title': manga_title or chapter_data.get('series', ''),
            'chapter_title': f"Chapter {chapter_data.get('chapter', '')}",
            'navigation': navigation,
            'images': images,
            'images_proxy': [f"/api/comic/proxy?url={quote(img)}" for img in images]
        }
        
        return result
    
    # ==================== HOME METHODS ====================
    
    def get_ranking(self, period: str = 'mingguan') -> List[Dict[str, Any]]:
        """Get ranking"""
        html_content = self.get_html_api(self.base_url)
        if not html_content:
            return []
        
        soup = BeautifulSoup(html_content, 'html.parser')
        
        panel = soup.find('div', id=f'rank-{period}')
        if not panel:
            panels = soup.find_all('div', class_='rank-panel')
            for p in panels:
                if p.get('id', '').endswith(period):
                    panel = p
                    break
        
        if not panel:
            return []
        
        results = []
        articles = panel.find_all('article', class_='ls4')
        
        for article in articles:
            try:
                img_wrap = article.find('div', class_='ls4v')
                if not img_wrap:
                    continue
                
                link = img_wrap.find('a')
                if not link:
                    continue
                
                url = link.get('href', '')
                slug = url.replace('/manga/', '').rstrip('/') if url else ''
                
                img = link.find('img')
                image_url = self._get_image_url(img)
                
                rank_span = img_wrap.find('span', class_='rank-num')
                rank = rank_span.get_text(strip=True) if rank_span else None
                
                info_div = article.find('div', class_='ls4j')
                if not info_div:
                    continue
                
                title_elem = info_div.find('h4')
                title_link = title_elem.find('a') if title_elem else None
                title = title_link.get_text(strip=True) if title_link else ''
                
                info_span = info_div.find('span', class_='ls4s')
                info_text = info_span.get_text(strip=True) if info_span else ''
                
                genre = ''
                views = ''
                if 'Ã‚Â·' in info_text:
                    parts = info_text.split('Ã‚Â·')
                    genre = parts[0].strip() if len(parts) > 0 else ''
                    views = parts[1].strip() if len(parts) > 1 else ''
                
                chapter_link = info_div.find('a', class_='ls24')
                latest_chapter = chapter_link.get_text(strip=True) if chapter_link else ''
                latest_chapter_url = chapter_link.get('href', '') if chapter_link else ''
                
                results.append({
                    'rank': int(rank) if rank else None,
                    'title': title,
                    'slug': slug,
                    'url': url,
                    'image': image_url,
                    'genre': genre,
                    'views': views,
                    'latest_chapter': latest_chapter,
                    'latest_chapter_url': latest_chapter_url
                })
                
            except Exception as e:
                continue
        
        return results
    
    def get_populer(self, tipe: str = 'semua') -> List[Dict[str, Any]]:
        """Get popular comics"""
        html_content = self.get_html_api(self.base_url)
        if not html_content:
            return []
        
        soup = BeautifulSoup(html_content, 'html.parser')
        
        container = soup.find('div', id='ls12-populer')
        if not container:
            container = soup.find('div', class_='ls12')
        
        if not container:
            return []
        
        results = []
        articles = container.find_all('article', class_='ls2')
        
        for article in articles:
            try:
                img_wrap = article.find('div', class_='ls2v')
                if not img_wrap:
                    continue
                
                link = img_wrap.find('a')
                if not link:
                    continue
                
                url = link.get('href', '')
                slug = url.replace('/manga/', '').rstrip('/') if url else ''
                
                img = link.find('img')
                image_url = self._get_image_url(img)
                
                flag_img = img_wrap.find('img', class_='flag')
                flag = flag_img.get('src', '').split('/')[-1].replace('.png', '') if flag_img else ''
                
                comic_type = article.get('data-tipe', '')
                
                up_span = img_wrap.find('span', class_='up')
                up = up_span.get_text(strip=True) if up_span else None
                
                info_div = article.find('div', class_='ls2j')
                if not info_div:
                    continue
                
                title_elem = info_div.find('h3')
                title_link = title_elem.find('a') if title_elem else None
                title = title_link.get_text(strip=True) if title_link else ''
                
                info_span = info_div.find('span', class_='ls2t')
                info_text = info_span.get_text(strip=True) if info_span else ''
                
                genre = ''
                views = ''
                if 'Ã‚Â·' in info_text:
                    parts = info_text.split('Ã‚Â·')
                    genre = parts[0].strip() if len(parts) > 0 else ''
                    views = parts[1].strip() if len(parts) > 1 else ''
                
                chapter_link = info_div.find('a', class_='ls2l')
                latest_chapter = chapter_link.get_text(strip=True) if chapter_link else ''
                latest_chapter_url = chapter_link.get('href', '') if chapter_link else ''
                
                if tipe == 'semua' or comic_type == tipe:
                    results.append({
                        'title': title,
                        'slug': slug,
                        'url': url,
                        'image': image_url,
                        'type': comic_type,
                        'flag': flag,
                        'up': up,
                        'genre': genre,
                        'views': views,
                        'latest_chapter': latest_chapter,
                        'latest_chapter_url': latest_chapter_url
                    })
                
            except Exception as e:
                continue
        
        return results
    
    def get_terbaru(self) -> List[Dict[str, Any]]:
        """Get latest comics"""
        html_content = self.get_html_api(self.base_url)
        if not html_content:
            return []
        
        soup = BeautifulSoup(html_content, 'html.parser')
        
        container = soup.find('div', class_='ls2-wrap')
        if not container:
            return []
        
        results = []
        articles = container.find_all('article', class_='ls2')
        
        for article in articles:
            try:
                img_wrap = article.find('div', class_='ls2v')
                if not img_wrap:
                    continue
                
                link = img_wrap.find('a')
                if not link:
                    continue
                
                url = link.get('href', '')
                slug = url.replace('/manga/', '').rstrip('/') if url else ''
                
                img = link.find('img')
                image_url = self._get_image_url(img)
                
                flag_img = img_wrap.find('img', class_='flag')
                flag = flag_img.get('src', '').split('/')[-1].replace('.png', '') if flag_img else ''
                
                comic_type = article.get('data-tipe', '')
                
                up_span = img_wrap.find('span', class_='up')
                up = up_span.get_text(strip=True) if up_span else None
                
                info_div = article.find('div', class_='ls2j')
                if not info_div:
                    continue
                
                title_elem = info_div.find('h3')
                title_link = title_elem.find('a') if title_elem else None
                title = title_link.get_text(strip=True) if title_link else ''
                
                info_span = info_div.find('span', class_='ls2t')
                info_text = info_span.get_text(strip=True) if info_span else ''
                
                time_ago = info_text if info_text else ''
                
                chapter_link = info_div.find('a', class_='ls2l')
                latest_chapter = chapter_link.get_text(strip=True) if chapter_link else ''
                latest_chapter_url = chapter_link.get('href', '') if chapter_link else ''
                
                results.append({
                    'title': title,
                    'slug': slug,
                    'url': url,
                    'image': image_url,
                    'type': comic_type,
                    'flag': flag,
                    'up': up,
                    'time_ago': time_ago,
                    'latest_chapter': latest_chapter,
                    'latest_chapter_url': latest_chapter_url
                })
                
            except Exception as e:
                continue
        
        return results