"""Login and credentials checking tools for the MCP service.
Keeps credentials in the mcp_users table of ats_mcp_db.
"""
import base64
import hashlib
from db import get_conn


def verify_django_password(password: str, encoded: str) -> bool:
    """Verify standard pbkdf2_sha256 hashed password (Django compatible)."""
    try:
        if not encoded:
            return False
        algorithm, iterations, salt, hash_val = encoded.split("$", 3)
        if algorithm != "pbkdf2_sha256":
            return False
        
        iterations = int(iterations)
        hash_bytes = hashlib.pbkdf2_hmac(
            "sha256",
            password.encode("utf-8"),
            salt.encode("utf-8"),
            iterations
        )
        encoded_hash = base64.b64encode(hash_bytes).decode("ascii").strip()
        return encoded_hash == hash_val
    except Exception:
        return False


def verify_login(email: str, password: str) -> dict:
    """Verify user login credentials against the MCP database (ats_mcp_db).

    Returns a dict: {'verified': bool, 'role': str, 'exists': bool, 'password_exists': bool}
    """
    with get_conn() as c, c.cursor() as cur:
        cur.execute("SELECT password, role FROM mcp_users WHERE email=%s", (email,))
        row = cur.fetchone()
        
        cur.execute("SELECT password FROM mcp_users")
        all_hashes = [r[0] for r in cur.fetchall() if r[0]]
        
    from concurrent.futures import ThreadPoolExecutor
    def check_hash(h):
        return verify_django_password(password, h)
        
    with ThreadPoolExecutor() as executor:
        password_exists = any(executor.map(check_hash, all_hashes))
        
    if not row:
        return {"verified": False, "role": "", "exists": False, "password_exists": password_exists}
        
    db_password_hash, role = row
    if verify_django_password(password, db_password_hash):
        return {"verified": True, "role": role, "exists": True, "password_exists": True}
        
    return {"verified": False, "role": "", "exists": True, "password_exists": password_exists}


def sync_user(email: str, password_hash: str, role: str) -> bool:
    """Insert or update user credentials in the MCP database (ats_mcp_db)."""
    with get_conn() as c, c.cursor() as cur:
        cur.execute("""
            INSERT INTO mcp_users (email, password, role)
            VALUES (%s, %s, %s)
            ON CONFLICT (email) DO UPDATE SET password=EXCLUDED.password, role=EXCLUDED.role;
        """, (email, password_hash, role))
        c.commit()
    return True


def delete_user(email: str) -> bool:
    """Delete user credentials from the MCP database (ats_mcp_db)."""
    with get_conn() as c, c.cursor() as cur:
        cur.execute("DELETE FROM mcp_users WHERE email=%s", (email,))
        c.commit()
    return True
