import frappe
import requests
from frappe.model.document import Document


MYGOVID_BASE_URL = "https://api.mygovid.gov.az"
MYGOVID_HEADERS = {
    "Accept": "application/json, text/plain, */*",
    "Accept-Language": "az",
    "Content-Type": "application/json",
    "Origin": "https://mygovid.gov.az",
    "Referer": "https://mygovid.gov.az/",
}


class testapi(Document):
    pass


@frappe.whitelist()
def start_asan_sign_login(user_id, phone_number, recaptcha_response=None):
    """
    Step 1: Initiate ASAN Sign login.
    This is a long-polling request that waits for user confirmation in ASAN Sign app.
    Returns JWT token after user confirms.
    """
    if not user_id or not phone_number:
        return {"success": False, "message": "User ID and phone number are required"}

    url = f"{MYGOVID_BASE_URL}/ssoauth/api/v1/logIn/asanSignLogin"

    payload = {
        "mobileKey": None,
        "phoneNumber": phone_number,
        "userId": user_id,
        "recaptcha3Response": recaptcha_response or "",
    }

    try:
        # Long timeout - waits for user to confirm in ASAN Sign app
        response = requests.post(
            url, json=payload, headers=MYGOVID_HEADERS, timeout=120
        )

        if response.status_code in [200, 201]:
            data = response.json()
            return {
                "success": True,
                "token": data.get("data", {}).get("token"),
                "transaction": data.get("transaction"),
                "response_data": data,
            }
        else:
            return {
                "success": False,
                "message": f"API error: status {response.status_code}",
                "response_data": response.text,
            }
    except requests.exceptions.Timeout:
        return {
            "success": False,
            "message": "Request timed out. User did not confirm in ASAN Sign app.",
        }
    except requests.exceptions.RequestException as e:
        frappe.log_error(f"MyGovID API error: {str(e)}", "MyGovID API Error")
        return {"success": False, "message": f"Network error: {str(e)}"}
    except Exception as e:
        frappe.log_error(
            f"MyGovID unexpected error: {str(e)}\n{frappe.get_traceback()}",
            "MyGovID API Error",
        )
        return {"success": False, "message": f"Error: {str(e)}"}


@frappe.whitelist()
def get_verification_code(user_id):
    """
    Step 2: Get verification code for ASAN Sign.
    Call this immediately after starting login to get the 4-digit code
    that user needs to confirm in ASAN Sign app.
    """
    if not user_id:
        return {"success": False, "message": "User ID is required"}

    url = f"{MYGOVID_BASE_URL}/ssoauth/api/v1/logIn/asanSignLogin/verificationCode/{user_id}"

    try:
        response = requests.get(url, headers=MYGOVID_HEADERS, timeout=30)

        if response.status_code in [200, 201]:
            data = response.json()
            return {
                "success": True,
                "code": data.get("data", {}).get("code"),
                "transaction": data.get("transaction"),
                "response_data": data,
            }
        else:
            return {
                "success": False,
                "message": f"API error: status {response.status_code}",
                "response_data": response.text,
            }
    except requests.exceptions.RequestException as e:
        frappe.log_error(f"MyGovID API error: {str(e)}", "MyGovID API Error")
        return {"success": False, "message": f"Network error: {str(e)}"}
    except Exception as e:
        frappe.log_error(
            f"MyGovID unexpected error: {str(e)}\n{frappe.get_traceback()}",
            "MyGovID API Error",
        )
        return {"success": False, "message": f"Error: {str(e)}"}