import asyncio
import base64
import os
import tempfile
import shutil
import time
from fastapi import FastAPI, HTTPException, Form
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# FastAPI ilovasini yaratish
app = FastAPI(
    title="Emaktab Screenshot API",
    description="Emaktab tizimiga kirish va screenshot olish uchun API",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# CORS sozlamalari
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Sozlamalar
VALID_SECRET_KEYS = {
    "my_secret_key_123",
    "test_key_456",
    "emaktab_api_key_789"
}

EMAKTAB_URL = "https://login.emaktab.uz/"

# Response modellari
class SuccessResponse(BaseModel):
    success: bool
    message: str
    screenshot: str  # base64 encoded image
    page_title: str
    current_url: str
    timestamp: str

class ErrorResponse(BaseModel):
    success: bool
    error: str
    timestamp: str

def setup_driver():
    """Har bir so‘rov uchun yangi Chrome instance yaratadi"""
    options = Options()
    options.add_argument("--headless=new")  # yangi headless rejim (Chrome 109+ uchun)
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--disable-gpu")
    options.add_argument("--window-size=1920,1080")
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)

    # Har bir sessiya uchun noyob profil
    user_data_dir = tempfile.mkdtemp(prefix="chrome_user_data_")
    options.add_argument(f"--user-data-dir={user_data_dir}")

    driver = webdriver.Chrome(options=options)

    # Brauzer yopilgach, profil papkani o‘chirish uchun yordamchi funksiya
    def cleanup():
        try:
            driver.quit()
        except Exception:
            pass
        try:
            shutil.rmtree(user_data_dir, ignore_errors=True)
        except Exception:
            pass

    # driver obyektiga tozalash funksiyasini biriktiramiz
    driver.cleanup = cleanup

    return driver


def validate_secret_key(secret_key: str):
    """Secret key ni tekshirish"""
    if secret_key not in VALID_SECRET_KEYS:
        raise HTTPException(
            status_code=401,
            detail="Noto'g'ri secret key"
        )

@app.post("/api/screenshot", response_model=SuccessResponse)
async def get_emaktab_screenshot(
    username: str = Form(..., description="Emaktab login"),
    password: str = Form(..., description="Emaktab parol"),
    secret_key: str = Form(..., description="API secret key")
):
    """
    Emaktab tizimiga kirish va screenshot olish
    """
    try:
        # Secret key ni tekshirish
        validate_secret_key(secret_key)
        
        print(f"🔐 Kirish urinishi: {username}")
        
        driver = None
        try:
            # Brauzerni ishga tushirish
            driver = setup_driver()
            
            # Sahifaga o'tish
            print("🌐 Sahifaga o'tilmoqda...")
            driver.get(EMAKTAB_URL)
            
            # Kutish va elementlarni topish
            wait = WebDriverWait(driver, 15)
            
            # Login maydonini topish va to'ldirish
            print("🔑 Login kiritilmoqda...")
            login_field = wait.until(EC.presence_of_element_located((By.NAME, "login")))
            login_field.clear()
            login_field.send_keys(username)
            
            # Parol maydonini topish va to'ldirish
            print("🔒 Parol kiritilmoqda...")
            password_field = driver.find_element(By.NAME, "password")
            password_field.clear()
            password_field.send_keys(password)
            
            # Submit tugmasini bosish
            print("📝 Kirish tugmasi bosilmoqda...")
            submit_btn = driver.find_element(By.XPATH, "//input[@type='submit']")
            submit_btn.click()
            
            # Natijani kutish
            print("⏳ Natija kutilyapti...")
            time.sleep(8)
            
            # Vaqinchalik fayl yaratish
            with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp_file:
                screenshot_path = tmp_file.name
            
            # Screenshot olish
            print("📸 Screenshot olinmoqda...")
            driver.save_screenshot(screenshot_path)
            
            # Screenshot ni base64 ga o'girish
            with open(screenshot_path, "rb") as image_file:
                base64_image = base64.b64encode(image_file.read()).decode('utf-8')
            
            # Vaqinchalik faylni o'chirish
            os.unlink(screenshot_path)
            
            print("✅ Muvaffaqiyatli yakunlandi")
            
            # Ma'lumotlarni qaytarish
            return SuccessResponse(
                success=True,
                message="Screenshot muvaffaqiyatli olindi",
                screenshot=base64_image,
                page_title=driver.title,
                current_url=driver.current_url,
                timestamp=time.strftime("%Y-%m-%d %H:%M:%S")
            )
            
        except Exception as e:
            error_msg = f"Brauzer jarayonida xatolik: {str(e)}"
            print(f"❌ {error_msg}")
            raise HTTPException(
                status_code=400,
                detail=error_msg
            )
            
        finally:
            if driver:
                driver.cleanup()
                print("✅ Brauzer yopildi va vaqtinchalik papkalar tozalandi")
                
    except HTTPException:
        raise
    except Exception as e:
        error_msg = f"Server xatosi: {str(e)}"
        print(f"❌ {error_msg}")
        raise HTTPException(
            status_code=500,
            detail=error_msg
        )

@app.get("/")
async def root():
    """Asosiy sahifa"""
    return {
        "message": "Emaktab Screenshot API", 
        "version": "1.0.0",
        "docs": "/docs",
        "endpoint": "POST /api/screenshot"
    }

@app.get("/health")
async def health_check():
    """Sog'lik tekshiruvi"""
    return {
        "status": "healthy", 
        "service": "Emaktab Screenshot API",
        "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
    }
