import os
import csv
import pandas as pd
from playwright.sync_api import sync_playwright
from PyPDF2 import PdfReader
from fpdf import FPDF
from PIL import Image
from io import BytesIO
import fitz  

def pixmap_to_image(pixmap):
    img_data = pixmap.samples
    img = Image.frombytes("RGB", [pixmap.width, pixmap.height], img_data)
    return img

def create_pdf_a6(input_pdf_path, output_4_per_page):
    """
    Create a PDF with 4 pages per A6 sheet.
    """
    print(f"Creating A6 format PDF from: {input_pdf_path}")
    doc = fitz.open(input_pdf_path) 
    pdf_4_per_page = FPDF() 

    for i in range(0, len(doc), 4):
        pdf_4_per_page.add_page()
        for j in range(4):
            page_idx = i + j
            if page_idx < len(doc):
                pixmap = doc.load_page(page_idx).get_pixmap()
                img = pixmap_to_image(pixmap)
                buffer = BytesIO()
                img.save(buffer, format="PNG")
                buffer.seek(0)

                
                x_offset = (j % 2) * 105
                y_offset = (j // 2) * 148.5
                pdf_4_per_page.image(buffer, x=x_offset, y=y_offset, w=105, h=148.5)

    pdf_4_per_page.output(output_4_per_page)  
    print(f"A6 PDF saved at: {output_4_per_page}")

def create_pdf_a5(input_pdf_path, output_2_per_page_landscape):
    """
    Create a PDF with 2 pages per A5 sheet in landscape orientation.
    """
    print(f"Creating A5 format PDF from: {input_pdf_path}")
    doc = fitz.open(input_pdf_path) 
    pdf_2_per_page_landscape = FPDF(orientation="L", unit="mm", format="A5") 

    for i in range(0, len(doc), 2):
        pdf_2_per_page_landscape.add_page()
        for j in range(2):
            page_idx = i + j
            if page_idx < len(doc):
                pixmap = doc.load_page(page_idx).get_pixmap()
                img = pixmap_to_image(pixmap)
                buffer = BytesIO()
                img.save(buffer, format="PNG")
                buffer.seek(0)

               
                x_offset = j * 148.5  # Half of A5 width
                y_offset = 0  
                pdf_2_per_page_landscape.image(buffer, x=x_offset, y=y_offset, w=148.5, h=210)

    pdf_2_per_page_landscape.output(output_2_per_page_landscape) 
    print(f"A5 Landscape PDF saved at: {output_2_per_page_landscape}")

def scrape_patent_data(patent_number, pdf_path):
    """
    Scrape patent data for a single patent number.
    Fetches details like Legal Status, Patent Number, Application Number, Dates, etc.
    Saves the page as a PDF.
    """
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)  
        page = browser.new_page()

        try:
            os.makedirs(os.path.dirname(pdf_path), exist_ok=True)

            print(f"Visiting the website for patent number: {patent_number}")
            page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
                      wait_until="domcontentloaded", timeout=60000)

            page.wait_for_selector('input[name="PatentNumber"]', timeout=60000)
            page.fill('input[name="PatentNumber"]', patent_number)

            print("Please enter the CAPTCHA manually in the browser and submit the form.")

            page.wait_for_url("https://iprsearch.ipindia.gov.in/PatentSearch/PatentSearch/eRegistrationReport", timeout=90000)  

            if page.locator("text=Sorry, we can't load the resource").is_visible():
                print(f"Failed to load data for patent number {patent_number}: Sorry, we can't load the resource")
                return None

            print(f"Successfully loaded e-Register page for patent number {patent_number}.")
            page.pdf(path=pdf_path, format="A4")  
            print(f"PDF saved: {pdf_path}")

            return pdf_path  # Return the path of the saved PDF

        except Exception as e:
            print(f"Error during scraping for patent number {patent_number}: {e}")
            return None

        finally:
            browser.close()

def get_pdf_page_count(pdf_path):
    """
    Get the number of pages in a PDF file.
    """
    with open(pdf_path, "rb") as f:
        reader = PdfReader(f)
        return len(reader.pages)

def safe_extract_text(locator, default='N/A'):
    """
    Safely extract text from a Playwright locator.
    """
    try:
        return locator.inner_text().strip()
    except Exception:
        return default

def save_to_csv(data, filename):
    """
    Append data to a CSV file.
    """
    if data:
        file_exists = os.path.isfile(filename)
        with open(filename, mode='a', newline='', encoding='utf-8') as file:
            writer = csv.DictWriter(file, fieldnames=data.keys())
            if not file_exists:
                writer.writeheader()
            writer.writerow(data)

if __name__ == "__main__":
    input_file = r"C:\Users\Administrator\Desktop\webscrapper\o1mini\Sample-Data-PatAnn.xlsx"
    output_file = "data4.csv"
    pdf_directory = "C:\\Users\\Administrator\\Desktop\\webscrapper\\pdfs"  
    os.makedirs(pdf_directory, exist_ok=True)

    print("Reading patent numbers from Excel file...")
    df = pd.read_excel(input_file)

    if 'Patent No.' not in df.columns:
        print("Column 'Patent No.' not found in Excel file.")
        exit()

    pdf_files = []  

    for idx, row in df.iterrows():
        patent_number = str(row['Patent No.'])
        print(f"\nProcessing patent number: {patent_number}")

        pdf_path = os.path.join(pdf_directory, f"{patent_number}.pdf") 
        scraped_data = scrape_patent_data(patent_number, pdf_path)
        
        if scraped_data:  
            num_pages = get_pdf_page_count(scraped_data)  # Get the number of pages in the created PDF
            print(f"Patent number {patent_number} PDF has {num_pages} page(s).")

            if num_pages <= 2:
                # Save as A5
                print(f"Saving {patent_number} PDF to A5 format.")
                create_pdf_a5(pdf_path, os.path.join(pdf_directory, f"{patent_number}_A5.pdf"))
            else:
                # Save as A6
                print(f"Saving {patent_number} PDF to A6 format.")
                create_pdf_a6(pdf_path, os.path.join(pdf_directory, f"{patent_number}_A6.pdf"))

            pdf_files.append(scraped_data)
            print(f"PDF for patent number {patent_number} saved at: {scraped_data}")
            print(f"Saving extracted data for patent number {patent_number}...")
            save_to_csv({
                'Patent Number': patent_number,
                'PDF Path': scraped_data
            }, output_file)

    print("All patents processed.")
    print(f"Total number of PDFs created: {len(pdf_files)}")
    print("Script execution completed.")   make chnges in this ...only for 2 page ......if 2 page are their print on a5 side by side not in lanscape