# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE
import os
import re
from pathlib import Path
from urllib.parse import urlencode

no_cache = 1

import json

import jingrow
import jingrow.sessions
from jingrow import _
from jingrow.utils.jinja_globals import is_rtl

SCRIPT_TAG_PATTERN = re.compile(r"\<script[^<]*\</script\>")
CLOSING_SCRIPT_TAG_PATTERN = re.compile(r"</script\>")


def get_context(context):
	# Let the frontend SPA handle authentication via router guards
	# Only block Website Users from accessing the app
	if jingrow.session.user != "Guest" and jingrow.db.get_value("User", jingrow.session.user, "user_type", order_by=None) == "Website User":
		jingrow.throw(_("You are not permitted to access this page."), jingrow.PermissionError)

	hooks = jingrow.get_hooks()
	try:
		boot = jingrow.sessions.get()
	except Exception as e:
		raise jingrow.SessionBootFailed from e

	# this needs commit
	csrf_token = jingrow.sessions.get_csrf_token()

	jingrow.db.commit()

	boot_json = jingrow.as_json(boot, indent=None, separators=(",", ":"))

	# remove script tags from boot
	boot_json = SCRIPT_TAG_PATTERN.sub("", boot_json)

	# TODO: Find better fix
	boot_json = CLOSING_SCRIPT_TAG_PATTERN.sub("", boot_json)

	# Parse frontend assets from dist/index.html
	frontend_assets = parse_frontend_assets()

	context.update(
		{
			"no_cache": 1,
			"boot": boot if context.get("for_mobile") else json.loads(boot_json),
			"csrf_token": csrf_token,
			"frontend_assets": frontend_assets,
		}
	)

	return context


def parse_frontend_assets():
	"""Parse frontend assets from dist/index.html"""
	app_path = Path(__file__).parent.parent
	frontend_index = app_path / "public" / "frontend" / "index.html"
	
	if not frontend_index.exists():
		return {"js": [], "css": []}
	
	try:
		html_content = frontend_index.read_text()
		
		# Extract JS files
		js_pattern = re.compile(r'<script[^>]*src="/assets/jingrow/frontend/assets/([^"]+\.js)"')
		js_files = [m.group(1) for m in js_pattern.finditer(html_content)]
		
		# Extract CSS files
		css_pattern = re.compile(r'<link[^>]*href="/assets/jingrow/frontend/assets/([^"]+\.css)"')
		css_files = [m.group(1) for m in css_pattern.finditer(html_content)]
		
		return {"js": js_files, "css": css_files}
	except Exception as e:
		jingrow.log_error(f"Failed to parse frontend assets: {str(e)}")
		return {"js": [], "css": []}
