"""Password utilities for jlocal environment."""

import requests
from jingrow.config import Config
from jingrow.utils.auth import get_jingrow_api_headers


def get_decrypted_password(pagetype, name, fieldname="password", raise_exception=True):
	"""Get decrypted password from remote Jingrow SaaS API."""
	headers = get_jingrow_api_headers()
	if not headers:
		if raise_exception:
			raise Exception("JINGROW_API_KEY or JINGROW_API_SECRET not configured")
		return None
	
	resp = requests.post(
		f"{Config.jingrow_server_url}/api/action/jingrow.client.get_password",
		headers=headers,
		json={"pagetype": pagetype, "name": name, "fieldname": fieldname},
		timeout=10
	)

	if resp.status_code == 200:
		result = resp.json()
		return result.get("message") if isinstance(result, dict) else result

	if raise_exception:
		raise Exception(f"Password not found for {pagetype} {name} {fieldname}")
