import hashlib
import jwt
import logging
import httpx
from datetime import datetime, timedelta
from fastapi import Header,Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jwt import ExpiredSignatureError, InvalidTokenError
from jinja2 import Environment, FileSystemLoader
from pathlib import Path
import requests
from typing import Optional
from app.core.config import settings
import base64

#oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login")
logger = logging.getLogger(__name__)
TEMPLATE_DIR = Path(__file__).resolve().parent.parent / "templates"
env = Environment(loader=FileSystemLoader(str(TEMPLATE_DIR)))

def get_Password_hash(password: str) -> str:
    return hashlib.sha256(password.encode('utf-8')).hexdigest()

def verify_password(plain_password: str, hashed_password: str) -> bool:
    return get_Password_hash(plain_password) == hashed_password

def create_access_token(data: dict) -> str:
    try:
        expire = datetime.now() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
        to_encode = data.copy()
        to_encode.update({"exp": expire})
        encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
        return encoded_jwt
    except Exception as e:
        print("Token generation failed:", str(e))
        raise HTTPException(status_code=500, detail="Token creation failed")

# def get_current_user(token: str) -> dict:
#     try:
#         payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
#         username: str = payload.get("sub")
#         role: str = payload.get("role")
#         user_id: int = payload.get("user_id")
#         if not username  or not role:
#             raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token missing email/role")
#         return {"username": username,"role": role,"user_id": user_id}
#     except ExpiredSignatureError:
#         raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired")
#     except InvalidTokenError:
#         raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
def get_current_user(authorization: Optional[str] = Header(None)) -> dict:
    if not authorization or not authorization.startswith("Bearer "):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, 
            detail="Authentication required. Please login to access this resource.",
            headers={"WWW-Authenticate": "Bearer"}
        )

    token = authorization.split(" ")[1]  # Extract actual token
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        username: str = payload.get("sub")
        role: str = payload.get("role")
        user_id: int = payload.get("user_id")
        name: str = payload.get("name")
        lastname: str = payload.get("lastname")
        if not username or not role:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED, 
                detail="Invalid token format. Please login again.",
                headers={"WWW-Authenticate": "Bearer"}
            )
        return {"username": username, "role": role, "user_id": user_id,"name": name,"lastname": lastname}
    except ExpiredSignatureError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, 
            detail="Session expired. Please login again.",
            headers={"WWW-Authenticate": "Bearer"}
        )
    except InvalidTokenError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, 
            detail="Invalid authentication token. Please login again.",
            headers={"WWW-Authenticate": "Bearer"}
        )

    
def send_reset_email(name: str, lastname: str, email: str, token: str, role: str):
    reset_paths = {
        "Applicant": "Applicant/reset-password",
        "Employer": "Employer/reset-password",
        "Attorney": "Attorney/reset-password",
        "Admin": "Admin/reset-password"
    }

    if role not in reset_paths:
        raise ValueError("Invalid role for email dispatch.")
    encoded_email = base64.b64encode(email.encode()).decode()
    reset_url = f"{settings.site_url}{reset_paths[role]}/{token}/{encoded_email}"

    # Render HTML from Jinja2 template
    template = env.get_template("reset_passwords.html")
    html_content = template.render(name=name, lastname=lastname, reset_url=reset_url)

    payload = {
        "from": {"email": "alerts@employmentexchange.com", "name": "H1bApplicants"},
        "subject": "Reset Password",
        "content": [{"type": "html", "value": html_content}],
        "personalizations": [{"to": [{"email": email}]}]
    }

    headers = {
        "api_key": settings.PEPIPOST_API_KEY,
        "content-type": "application/json"
    }

    response = requests.post("https://api.pepipost.com/v5.1/mail/send", json=payload, headers=headers)
    response.raise_for_status()

def send_activation_email(name: str, lastname: str, email: str, role: str):
    reset_paths = {
        "Applicant": "Applicant/create-password",
        "Employer": "Employer/create-password",
        "Attorney": "Attorney/create-password",
        "Admin": "Admin/create-password"
    }

    if role not in reset_paths:
        raise ValueError("Invalid role for email dispatch.")
    
    encoded_email = base64.b64encode(email.encode()).decode()
    reset_url = f"{settings.site_url}{reset_paths[role]}/{encoded_email}"

    try:
        template = env.get_template("activation_mail.html")
        html_content = template.render(name=name, lastname=lastname, reset_url=reset_url)

        payload = {
            "from": {"email": "alerts@employmentexchange.com", "name": "H1bApplicants"},
            "subject": "Activation Mail",
            "content": [{"type": "html", "value": html_content}],
            "personalizations": [{"to": [{"email": email}]}]
        }

        headers = {
            "api_key": settings.PEPIPOST_API_KEY,
            "content-type": "application/json"
        }

        response = requests.post(
            "https://api.pepipost.com/v5.1/mail/send",
            json=payload,
            headers=headers
        )
        response.raise_for_status()

    except requests.RequestException as e:
        logger.error(f"Email sending failed: {e}")
        logger.error(f"Response content: {getattr(e.response, 'text', 'No response')}")
        raise RuntimeError("User created, but email sending failed") from e
    return True
def send_ticket_email_to_employers(employers, applicant_data: dict, subject: str, msg: str):
    template = env.get_template("ticket_notification_mail.html")

    for emp in employers:
        html_content = template.render(
            employer_name=f"{emp.name.capitalize()} {emp.lastname.capitalize()}",
            applicant_name=f"{applicant_data['name'].capitalize()} {applicant_data['lastname'].capitalize()}",
            login_url=f"{settings.site_url}Employer/Login",
            notification_msg=msg
        )

        payload = {
            "from": {"email": "alerts@employmentexchange.com", "name": "H1bApplicants"},
            "subject": subject,
            "content": [{"type": "html", "value": html_content}],
            "personalizations": [{"to": [{"email": emp.email}]}]
        }

        headers = {
            "api_key": settings.PEPIPOST_API_KEY,
            "content-type": "application/json"
        }

        try:
            with httpx.Client() as client:
                response = client.post(
                    "https://api.pepipost.com/v5.1/mail/send",
                    json=payload,
                    headers=headers
                )
                response.raise_for_status()
        except httpx.HTTPError as email_err:
            print(f"Failed to send email to {emp.email}: {email_err}")
def send_invitation_mail(useremail: str, email: Optional[str] = None):
    template = env.get_template("activation_mail.html")
    reset_url = f"https://www.h1bapplicants.com/"
    html_content = template.render(user='User', reset_url=reset_url)
    
    payload = {
        "from": {"email": "alerts@employmentexchange.com", "name": "H1bApplicants"},
        "subject": "Invitation Mail",
        "content": [{"type": "html", "value": html_content}],
        "personalizations": [{"to": [{"email": useremail}]}]
    }

    headers = {
        "api_key": settings.PEPIPOST_API_KEY,
        "content-type": "application/json"
    }

    response = requests.post(
        "https://api.pepipost.com/v5.1/mail/send",
        json=payload,
        headers=headers
    )
    response.raise_for_status()