import asyncio
import base64
import os
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
import time
import tempfile

# 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=["*"],  # Productionda aniq domenlarni ko'rsating
    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():
    """Chrome driver ni sozlash"""
    options = Options()
    options.add_argument("--headless")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--window-size=1920,1080")
    options.add_argument("--disable-gpu")
    options.add_argument("--remote-debugging-port=9222")
    options.add_argument("--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
    
    return webdriver.Chrome(options=options)

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.quit()
                print("✅ Brauzer yopildi")
                
    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": "https://bot.pdev.uz/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")
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)Ï