from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from packaging import version

from app.db.database import get_db
from app.models.models import Version, License
from app.schemas.license import VersionCheckRequest, VersionCheckResponse
from app.core.security import get_api_key

router = APIRouter()

@router.post("/check", response_model=VersionCheckResponse)
async def check_version(
    request: VersionCheckRequest,
    db: Session = Depends(get_db),
    api_key = Depends(get_api_key)
):
    license = db.query(License).filter(
        License.license_key == request.license_key,
        License.is_active == True
    ).first()
    
    if not license:
        return VersionCheckResponse(
            latest_version=request.current_version,
            current_version=request.current_version,
            update_available=False,
            is_mandatory=False
        )
    
    latest_version = db.query(Version).order_by(Version.release_date.desc()).first()
    
    if not latest_version:
        return VersionCheckResponse(
            latest_version=request.current_version,
            current_version=request.current_version,
            update_available=False,
            is_mandatory=False
        )
    
    current_ver = version.parse(request.current_version)
    latest_ver = version.parse(latest_version.version_number)
    
    update_available = latest_ver > current_ver
    is_mandatory = False
    
    if update_available and latest_version.is_mandatory:
        if latest_version.min_version:
            min_ver = version.parse(latest_version.min_version)
            is_mandatory = current_ver < min_ver
        else:
            is_mandatory = True
    
    return VersionCheckResponse(
        latest_version=latest_version.version_number,
        current_version=request.current_version,
        update_available=update_available,
        is_mandatory=is_mandatory,
        download_url=latest_version.download_url if update_available else None,
        release_notes=latest_version.release_notes if update_available else None
    )

@router.get("/latest")
async def get_latest_version(
    db: Session = Depends(get_db),
    api_key = Depends(get_api_key)
):
    latest_version = db.query(Version).order_by(Version.release_date.desc()).first()
    
    if not latest_version:
        return {
            "version": "1.0.0",
            "release_date": None,
            "release_notes": "Initial release"
        }
    
    return {
        "version": latest_version.version_number,
        "release_date": latest_version.release_date,
        "is_mandatory": latest_version.is_mandatory,
        "min_version": latest_version.min_version,
        "download_url": latest_version.download_url,
        "release_notes": latest_version.release_notes
    }