import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
from typing import List

class TopMoversFetcher:
    @staticmethod
    def _extract_symbol_from_href(href: str) -> str:
        """
        Extract symbol from href like
        '/glenmark-pharmaceuticals-ltd/stocks/companyid-4255.cms'
        Returns: GLENMARK_PHARMACEUTICALS_LTD
        """
        parts = href.split('/stocks')[0]
        return parts.split('/')[-1].upper().replace('-', '_')

    def fetch_with_selenium(self, url: str = "https://economictimes.indiatimes.com/stocks/marketstats/top-gainers") -> List[str]:
        # Configure headless Chrome
        opts = Options()
        opts.headless = True
        driver = webdriver.Chrome(options=opts)

        try:
            driver.get(url)
            # Give the page JS time to load all 100 rows (adjust sleep if necessary)
            time.sleep(5)

            soup = BeautifulSoup(driver.page_source, 'html.parser')
            rows = soup.select("#table tbody tr")    # should now be all 100

            gainers: List[str] = []
            for row in rows:
                a = row.select_one("a.MarketTable_ellipses__M8PxM")
                if not a:
                    continue
                href = a.get("href", "")
                try:
                    sym = self._extract_symbol_from_href(href)
                    gainers.append(sym)
                except Exception:
                    # malformed href?
                    continue

            return gainers

        finally:
            driver.quit()

if __name__ == "__main__":
    fetcher = TopMoversFetcher()
    gainers = fetcher.fetch_with_selenium()
    print(f"Found {len(gainers)} gainers:")
    print(gainers)
