import time
import os
from playwright.sync_api import sync_playwright


def solve_captcha(captcha_image_path):
    """
    Simulate a CAPTCHA solving process manually as 
    this version assumes manual entry for now.
    """
    print("Manual CAPTCHA solving required. Please solve the CAPTCHA:")
    solved_captcha = input("Enter the CAPTCHA value displayed in the image: ")
    return solved_captcha


def scrape_patent_data(patent_number):
    """
    Scrape patent data for a single patent number.
    """
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)  # Set `headless=False` to see what happens
        page = browser.new_page()

        try:
            # Visit website
            page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister", 
                      wait_until="domcontentloaded", timeout=60000)
            print("Page loaded successfully.")

            # Wait for the search form to load and fill details
            page.wait_for_selector('input[name="PatentNumber"]', timeout=60000)  # Wait up to 60 seconds
            page.fill('input[name="PatentNumber"]', patent_number)

            # Wait for CAPTCHA to load and capture the image
            page.wait_for_selector('#Captcha', timeout=60000)
            captcha_element = page.locator('#Captcha')
            captcha_path = 'captcha.png'
            captcha_element.screenshot(path=captcha_path)
            print("CAPTCHA image saved as captcha.png.")

            # Solve the CAPTCHA (manual input for speed here)
            captcha_text = solve_captcha(captcha_path)

            # Fill the CAPTCHA and submit
            page.fill('input[name="CaptchaText"]', captcha_text)
            page.click('input[name="submit"]')

            # Wait for the search results to load
            page.wait_for_load_state('networkidle', timeout=60000)  # Wait until network is idle

            # Check for error message in case CAPTCHA/data is incorrect
            error_message_locator = page.locator('.error-message, .alert-danger')
            if error_message_locator.count() > 0:
                print("Error:", error_message_locator.text_content().strip())
                return None

            print("Fetching Patent Data...")

            # Extract key details now, ensuring relevant locators are robust
            legal_status = safe_extract_text(page.locator('tr:has-text("Legal Status :") td:nth-child(2)'))
            date_of_expiry = safe_extract_text(page.locator('tr:has-text("Date of Expiry :") td:nth-child(2)'))
            if date_of_expiry == 'N/A':
                date_of_expiry = safe_extract_text(page.locator('tr:has-text("Due Date of Next Renewal :") td:nth-child(2)'))

            patent_number_text = safe_extract_text(page.locator('tr:has-text("Patent Number") td:nth-child(3)'))
            application_number = safe_extract_text(page.locator('tr:has-text("Application Number") td:nth-child(3)'))
            grant_title = safe_extract_text(page.locator('tr:has-text("Grant Title") td:nth-child(3), tr:has-text("Grant Title") td[colspan="4"]'))
            patentee_name = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(2)'))
            patentee_type = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(3)'))

            # Extract last valid renewal details
            renewal_table = page.locator('table#renual tbody')
            row_count = renewal_table.locator('tr').count()

            last_valid_row = None
            for i in range(row_count - 1, 1, -1):  # Iterate from the last row, skip headers
                row = renewal_table.locator('tr').nth(i)
                row_text = row.text_content().strip()
                # Validate row content
                if "--" not in row_text and row_text.strip():
                    last_valid_row = row_text
                    break

            renewal_details = last_valid_row if last_valid_row else "No valid renewal details found"

            # Output the results
            print(f"Legal Status: {legal_status}")
            print(f"Date of Expiry: {date_of_expiry}")
            print(f"Patent Number: {patent_number_text}")
            print(f"Application Number: {application_number}")
            print(f"Grant Title: {grant_title}")
            print(f"Name of Patentee: {patentee_name}")
            print(f"Patentee Type: {patentee_type}")
            print(f"Last Renewal Details: {renewal_details}")

            # Return results as a dictionary
            return {
                'legal_status': legal_status,
                'date_of_expiry': date_of_expiry,
                'patent_number': patent_number_text,
                'application_number': application_number,
                'grant_title': grant_title,
                'patentee_name': patentee_name,
                'patentee_type': patentee_type,
                'renewal_details': renewal_details,
            }

        except Exception as e:
            print("Error during scraping:", e)
            return None

        finally:
            # Clean up the captcha file if it exists
            if os.path.exists(captcha_path):
                os.remove(captcha_path)
            browser.close()


def safe_extract_text(locator, default='N/A'):
    """
    Safely extract text from a locator. 
    Returns a default value if extraction fails.
    """
    try:
        return locator.text_content().strip()
    except Exception:
        return default


if __name__ == "__main__":
    # Test for a single patent number
    test_patent_number = "378120"  # Replace with the actual patent number to test
    print(f"Scraping data for Patent Number: {test_patent_number}")
    scraped_data = scrape_patent_data(test_patent_number)

    if scraped_data:
        print("Scraping completed successfully. Here are the details:")
        for key, value in scraped_data.items():
            print(f"{key}: {value}")
    else:
        print("Failed to scrape patent details.")    in this we are getting Legal Status,Date of Expiry,Patent Number,Application Number,Grant Title,Name of Patentee,Patentee Type,Last Renewal Details
Inforce,08/12/2025,N/A ,N/A,MEDICAL APPLIANCE WITH A HEATER,FRESENIUS MEDICAL CARE DEUTSCHLAND GMBH,OTHER THAN NATURAL PERSON,14th year
                                    08/12/2024
                                    08/06/2025

                                    73380
                                    05/12/2024
                                    24000

                                    170941
                                    05/12/2024
                                    08/12/2024
                                    08/12/2025   ..NOT DIsplaying patent number and appliaction number..ftech patent number from the number netered itself ....and after legal status i want a column date ....inisde which you have to mention Date of expiry or Due date of next renewal  as text ....becoz some patent no have date of next renewal and some have expiry date at the same place.....so first one column which date is it then in next column the date itself .....also in 7th column we want last renewakl year only like 14th or 11th or whatever and next to it we want the two columns from this 14th or 11th wjatever year is last having column name renewal amount and date of renewal in two separte columns        so i want lke inforce, Date of expiry , 08/12/2025, 317124, ...mention application no,name of pantentee,last renewal year, Renewal amount , REnwal date