#!/usr/bin/env python3
"""Scraper CMA CGM - undetected_chromedriver"""

import sys
import json
import time
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def scrap_cma(container):
    """Scrape CMA CGM using direct URL with container"""
    options = uc.ChromeOptions()
    options.add_argument("--disable-gpu")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-blink-features=AutomationControlled")
    
    driver = uc.Chrome(options=options)
    
    try:
        # Use direct URL with container parameter
        url = f"https://www.cma-cgm.com/ebusiness/tracking/detail/{container}"
        print(f"[CMA] Loading: {url}", file=sys.stderr)
        driver.get(url)
        time.sleep(8)
        
        # Accept cookies
        try:
            driver.execute_script("document.getElementById('onetrust-accept-btn-handler').click();")
            time.sleep(2)
        except:
            pass
        
        # Extract ETA - look for date patterns in timeline
        xpath_attempts = [
            "//div[contains(@class, 'timeline')]//span[contains(text(), '202')]",
            "//div[contains(@class, 'timeline--item-eta')]//span",
            "//div[@class='timeline-event']//div[@class='date-value']",
            "//span[@class='date-value']"
        ]
        
        eta = None
        for xpath in xpath_attempts:
            try:
                elements = driver.find_elements(By.XPATH, xpath)
                if elements:
                    eta = elements[0].text.strip()
                    if eta and len(eta) > 5:
                        print(f"[CMA] Found date: {eta}", file=sys.stderr)
                        break
            except:
                continue
        
        driver.quit()
        return eta if eta else "No Encontrado"
        
    except Exception as e:
        try:
            driver.quit()
        except:
            pass
        print(f"[CMA] Error: {str(e)[:100]}", file=sys.stderr)
        return f"Error"

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print(json.dumps({"error": "Missing container"}))
        sys.exit(1)
    
    container = sys.argv[1]
    print(f"[CMA] Starting scraper for: {container}", file=sys.stderr)
    eta = scrap_cma(container)
    print(json.dumps({"eta": eta, "container": container}))
