from pathlib import Path
from typing import Annotated, Optional
from fastapi.responses import JSONResponse
from pydantic import EmailStr
from schemas.admin import AdminCreateRequest, LoginSchemaAdmin
from utility.auth_token import get_current_admin, get_current_user
from core.generate_otp import generate_otp
from datetime import datetime, timedelta
from core.excption import NotFoundException
from schemas.users import CompleteSignupRequest, ForgotPasswordRequest, LoginSchema, PreSignupRequest, ResetPasswordRequest, UserUpdate, VerifyOtpRequest
from sqlalchemy.orm import Session
from models.models import User,AdminUser
from core.hash_password import Hasher
from fastapi import  BackgroundTasks, Form, status,HTTPException, Depends, Request, logger
from core.config import settings
from database import get_db
from models.models import User, Country, City
import uuid
from utility.auth_token import create_access_token,create_refresh_token
from fastapi import HTTPException, UploadFile, File
from sqlalchemy.orm import Session
import logging
logger = logging.getLogger(__name__)

async def create_admin_count(request_data: AdminCreateRequest, db: Session):
    existing_admin = db.query(AdminUser).filter(AdminUser.email == request_data.email).first()
    if existing_admin:
        raise HTTPException(status_code=400, detail="Admin with this email already exists")
    
    hashed_password = Hasher.get_password_hash(request_data.password)
    
    new_admin = AdminUser(
        id=str(uuid.uuid4()),
        email=request_data.email,
        full_name=request_data.full_name,
        phone_number=request_data.phone_number,
        password=hashed_password,
        is_admin=True,
        role="admin",
        active=True
        
    )
    
    db.add(new_admin)
    db.commit()
    db.refresh(new_admin)
    
    logger.info(f"New admin created: {new_admin.email}")
    
    return {"success": True, "message": "Admin account created successfully", "admin_id": new_admin.id}

async def login_admin(request_data: LoginSchemaAdmin, db: Session):
    admin_user = db.query(AdminUser).filter(AdminUser.email == request_data.email, AdminUser.is_admin == True).first()
    if not admin_user:
        raise HTTPException(status_code=404, detail="Admin user not found")
    
    if not Hasher.verify_password(request_data.hashed_password, admin_user.password):
        raise HTTPException(status_code=401, detail="Invalid credentials")
    
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": admin_user.email}, expires_delta=access_token_expires
    )
    refresh_token = create_refresh_token(data={"sub": admin_user.email})
    
    logger.info(f"Admin logged in: {admin_user.email}")
    
    return {
        "access_token": access_token,
        "refresh_token": refresh_token,
        "token_type": "bearer"
    }
    
    
async def get_admin_profile(current_admin: Annotated[AdminUser, Depends(get_current_admin)]):
    return {
        "id": current_admin.id,
        "email": current_admin.email,
        "full_name": current_admin.full_name,
        "phone_number": current_admin.phone_number,
        "is_admin": current_admin.is_admin,
        "role": current_admin.role,
        "active": current_admin.active
    }