"""
NAS API Authentication
Handle OTP login and authentication.
"""

import requests
from typing import Tuple, Optional

from .config import BASE_URL, USERNAME, PASSWORD, session, logger
from .session import save_sid
from .exceptions import NASAuthenticationError, NASConnectionError


def login_with_otp(otp_code: str) -> str:
    """
    Login to NAS with OTP code.
    Returns the session ID (SID) on success.
    Raises NASAuthenticationError on failure.
    """
    try:
        auth_url = f"{BASE_URL}/auth.cgi"
        auth_params = {
            "api": "SYNO.API.Auth",
            "version": "6",
            "method": "login",
            "account": USERNAME,
            "passwd": PASSWORD,
            "session": "FileStation",
            "format": "sid",
            "otp_code": otp_code
        }

        resp = session.get(auth_url, params=auth_params,
                           verify=False, timeout=30)
        resp.raise_for_status()

        data = resp.json()
        if data.get("success"):
            sid = data["data"]["sid"]
            save_sid(sid)
            logger.debug("NAS login successful")
            return sid
        else:
            error_msg = data.get("error", {})
            logger.error(f"NAS login failed: {error_msg}")
            raise NASAuthenticationError(
                f"Đăng nhập NAS thất bại: {error_msg}")

    except requests.exceptions.RequestException as e:
        logger.error(f"Network error during NAS login: {e}")
        raise NASConnectionError(f"Lỗi kết nối NAS: {e}")
    except Exception as e:
        logger.error(f"Unexpected error during NAS login: {e}")
        raise NASAuthenticationError(f"Lỗi đăng nhập NAS: {e}")


def authenticate_with_otp(otp_code: str) -> Tuple[str, Optional[str]]:
    """
    Authenticate with OTP and save session.

    Args:
        otp_code: The OTP code from user

    Returns:
        Tuple[str, Optional[str]]:
        - status: "success" or "error"
        - message: Success message or error description
    """
    try:
        sid = login_with_otp(otp_code)
        return "success", "Đăng nhập thành công"

    except NASAuthenticationError as e:
        return "error", str(e)
    except NASConnectionError as e:
        return "error", str(e)
    except Exception as e:
        logger.error(f"Unexpected error during OTP authentication: {e}")
        return "error", f"Lỗi đăng nhập: {e}"
