import uuid
import frappe
import requests

BASE_URL = "https://new.e-taxes.gov.az/api/po/authless/public/v1/authless"
SERVICE_CODE = "findTaxpayerByTinAndName"


@frappe.whitelist(allow_guest=True)
def lookup(voen):
	"""Lookup organization info by VOEN (TIN) from Azerbaijan e-taxes portal."""
	voen = str(voen).strip()
	if not voen:
		frappe.throw("VOEN is required")

	try:
		# Client-generated session ID (same for all requests)
		session_id = str(uuid.uuid4())

		# Step 1: register service usage, get serviceUsageId
		r1 = requests.post(
			f"{BASE_URL}/informational-service-usage",
			json={"serviceCode": SERVICE_CODE, "status": "provided", "loginMethod": "unregistered"},
			headers={"sessionId": session_id},
			timeout=10,
		)
		r1.raise_for_status()

		# Step 2: find taxpayer by TIN
		r2 = requests.post(
			f"{BASE_URL}/findTaxpayer",
			json={"middleName": None, "type": "legalEntity", "tin": voen, "serviceCode": SERVICE_CODE},
			headers={"sessionId": session_id},
			timeout=10,
		)
		r2.raise_for_status()
		data = r2.json()

		taxpayers = data.get("taxpayers", [])
		if not taxpayers:
			return {"success": False, "message": "Organization not found for this VOEN"}

		tp = taxpayers[0]
		legal = tp.get("legalTaxpayerStatus", {})

		return {
			"success": True,
			"name": tp.get("name", ""),
			"tin": tp.get("tin", ""),
			"active": tp.get("active", False),
			"vat_payer": tp.get("vatPayer", False),
			"organization_type": tp.get("organizationType", ""),
			"legal_address": legal.get("legalAddress", ""),
			"director": legal.get("legitimate", ""),
		}

	except requests.exceptions.Timeout:
		frappe.throw("Request to e-taxes.gov.az timed out. Please try again.")
	except requests.exceptions.RequestException as e:
		frappe.log_error(f"VOEN lookup error: {e}", "VOEN Lookup")
		frappe.throw("Failed to connect to e-taxes.gov.az. Please try again.")
