#!/usr/bin/env python3
import requests
from bs4 import BeautifulSoup
import json
import pandas as pd
import re
from typing import Dict, List
import logging

# Set up logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

class CVPRScraper:
    def __init__(self, url: str):
        self.url = url
        self.base_url = "https://openaccess.thecvf.com"
        
    def fetch_page(self) -> str:
        """Fetch the webpage content."""
        try:
            response = requests.get(self.url)
            response.raise_for_status()
            return response.text
        except requests.RequestException as e:
            logger.error(f"Error fetching page: {e}")
            raise

    def extract_paper_info(self, title_elem, authors_dd, links_dd) -> Dict:
        """Extract information for a single paper."""
        try:
            # Extract title and title link
            title_link_elem = title_elem.find("a")
            title = title_link_elem.text.strip()
            title_link = self.base_url + title_link_elem["href"]
            
            # Extract authors
            authors = [form.find("a").text.strip() for form in authors_dd.find_all("form")]
            
            # Extract links and bibtex
            pdf_link = None
            supp_link = None
            arxiv_link = None
            bibtex = None
            
            # Find all links in the links_dd element
            for link in links_dd.find_all("a", href=True):
                if link.text.strip().lower() == "pdf":
                    pdf_link = self.base_url + link["href"]
                elif link.text.strip().lower() == "supp":
                    supp_link = self.base_url + link["href"]
                elif link.text.strip().lower() == "arxiv":
                    arxiv_link = link["href"]
            
            # Extract bibtex from the bibref div
            bibtex_div = links_dd.find("div", class_="bibref")
            if bibtex_div:
                bibtex = bibtex_div.get_text(strip=True)
            
            return {
                "title": title,
                "title_link": title_link,
                "authors": authors,
                "pdf_link": pdf_link,
                "supplementary_link": supp_link,
                "arxiv_link": arxiv_link,
                "bibtex": bibtex
            }
        except Exception as e:
            logger.error(f"Error extracting paper info for title '{title if 'title' in locals() else 'unknown'}': {e}")
            return None

    def scrape(self) -> List[Dict]:
        """Scrape all papers from the page."""
        html = self.fetch_page()
        soup = BeautifulSoup(html, 'html.parser')
        
        papers = []
        # Find all paper titles
        title_elements = soup.find_all("dt", class_="ptitle")
        total_papers = len(title_elements)
        logger.info(f"Found {total_papers} papers")
        
        for i, title_elem in enumerate(title_elements, 1):
            try:
                # Get the next two dd elements after the title
                authors_dd = title_elem.find_next("dd")
                links_dd = authors_dd.find_next("dd")
                
                paper_info = self.extract_paper_info(title_elem, authors_dd, links_dd)
                if paper_info:
                    papers.append(paper_info)
                
                if i % 50 == 0:
                    logger.info(f"Processed {i}/{total_papers} papers")
            except Exception as e:
                logger.error(f"Error processing paper {i}: {e}")
                continue
        
        return papers

    def save_json(self, papers: List[Dict], output_file: str = "cvpr.json"):
        """Save papers to JSON file."""
        try:
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(papers, f, indent=2, ensure_ascii=False)
            logger.info(f"Saved JSON data to {output_file}")
        except Exception as e:
            logger.error(f"Error saving JSON file: {e}")

    def save_excel(self, papers: List[Dict], output_file: str = "cvpr.xlsx"):
        """Save papers to Excel file."""
        try:
            # Convert authors list to string
            papers_for_excel = []
            for paper in papers:
                paper_copy = paper.copy()
                paper_copy['authors'] = '; '.join(paper_copy['authors'])
                papers_for_excel.append(paper_copy)
            
            df = pd.DataFrame(papers_for_excel)
            df.to_excel(output_file, index=False, engine='openpyxl')
            logger.info(f"Saved Excel data to {output_file}")
        except Exception as e:
            logger.error(f"Error saving Excel file: {e}")

def main():
    url = "https://openaccess.thecvf.com/CVPR2024?day=all"
    scraper = CVPRScraper(url)
    
    try:
        papers = scraper.scrape()
        logger.info(f"Successfully scraped {len(papers)} papers")
        
        # Save to both formats
        scraper.save_json(papers)
        scraper.save_excel(papers)
        
    except Exception as e:
        logger.error(f"Error in main execution: {e}")
        raise

if __name__ == "__main__":
    main() 