"""Server-side HTML rendering."""
from __future__ import annotations
from copy import deepcopy
import re
from typing import Any
from .analytics import completion_stats
from .ballot import comparison_rows
from .data_sources import COUNTRIES, get_jurisdiction, list_countries, list_regions
from .education import learning_model
from .feedback import analyze_feedback
from .google_services import (
CalendarService,
GeminiService,
OAuthService,
TranslateService,
google_services_status,
)
from .integrations import google_maps_embed_configured, google_maps_embed_url, google_maps_directions_url
from .polling import alternatives_within_10_miles, assigned_location
from .registration import eligibility, registration_status, resolution_steps
from .security import cryptography_available
from .seed_data import INCIDENT_TYPES, LANGUAGES, META, TRANSLATIONS
from .timeline import days_until, deadlines_within_24_months, is_critical, next_deadline
from .utils import current_year, html, list_html, tag_html
from .voting import selected_method
def tr(state: dict[str, Any], key: str) -> str:
"""Handle tr."""
language = state.get("language", "en")
return TRANSLATIONS.get(language, TRANSLATIONS["en"]).get(key, TRANSLATIONS["en"].get(key, key))
def _override_key(state: dict[str, Any]) -> str:
return f"{state.get('country_code', 'US')}:{state.get('jurisdiction_id', '')}"
def _merge_nested(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
result = deepcopy(base)
for key, value in override.items():
if isinstance(result.get(key), dict) and isinstance(value, dict):
result[key] = _merge_nested(result[key], value)
else:
result[key] = deepcopy(value)
return result
def current_jurisdiction(state: dict[str, Any]) -> dict[str, Any]:
"""Return jurisdiction."""
jurisdiction = deepcopy(get_jurisdiction(state.get("country_code", "US"), state.get("jurisdiction_id", "")))
override = state.get("jurisdiction_overrides", {}).get(_override_key(state), {})
if override:
jurisdiction = _merge_nested(jurisdiction, override)
return jurisdiction
def current_language(state: dict[str, Any]) -> dict[str, Any]:
"""Return language."""
return next((item for item in LANGUAGES if item["code"] == state.get("language")), LANGUAGES[0])
def options(items: list[tuple[str, str]], selected: str) -> str:
"""Handle options."""
return "".join(
f''
for value, label in items
)
def flash_html(messages: list[str]) -> str:
"""Handle flash html."""
if not messages:
return ""
return '
' + " ".join(html(message) for message in messages) + "
"
def _nav_link(label: str, page_id: str, current: str) -> str:
"""Render a single navigation link with active state."""
active = ' class="nav-active" aria-current="page"' if page_id == current else ""
return f'{html(label)}'
def _is_placeholder_candidate(candidate: dict[str, Any]) -> bool:
return candidate.get("id") == "manual-candidate-notes"
def _coverage_summary(jurisdiction: dict[str, Any]) -> str:
if jurisdiction.get("country") == "IN":
assembly = jurisdiction.get("contacts", {}).get("assembly_seats")
lok_sabha = jurisdiction.get("contacts", {}).get("lok_sabha_seats")
if assembly and assembly != "0":
return (
f"{jurisdiction['name']} includes {assembly} assembly constituencies and "
f"{lok_sabha} Lok Sabha seats. Local ward coverage still requires official sources."
)
return (
f"{jurisdiction['name']} includes {lok_sabha} Lok Sabha seat(s). "
"State assembly or local ward coverage still requires official sources."
)
return f"{jurisdiction['country_name']} coverage is tailored to {jurisdiction['name']} using the configured {jurisdiction.get('district_label', 'district').lower()} label."
def render_onboarding(state: dict[str, Any]) -> str:
"""Render onboarding."""
birth_year_max = current_year()
country_code = state.get("country_code", "US")
country = COUNTRIES.get(country_code, COUNTRIES["US"])
jurisdiction_options = [(key, value) for key, value in list_regions(country_code).items()]
return f"""
Welcome
Set up your election assistant
Choose your country and voting area to tailor deadlines, registration guidance, ballot research, and polling details.
{html(jurisdiction['name'])}, {html(jurisdiction.get('country_name', ''))} deadlines are shown in {html(jurisdiction['timezone_label'])}. {html(tr(state, "mock"))}
Election tasks, deadlines, and voting options in one focused workspace.
Ask the AI Assistant
Powered by Google Gemini{' - API configured' if GeminiService.configured() else ' (offline FAQ mode)'}.
"""
def render_process(state: dict[str, Any], jurisdiction: dict[str, Any]) -> str:
"""Render process."""
steps = jurisdiction["process_steps"]
first_open = next((step["id"] for step in steps if not state.get("completed_steps", {}).get(step["id"])), "")
cards = []
for index, step in enumerate(steps, start=1):
complete = bool(state.get("completed_steps", {}).get(step["id"]))
current = step["id"] == first_open
status = "Complete" if complete else "Current" if current else "Upcoming"
cards.append(f"""
Use the browser print command for the print-optimized guide layout. PWA offline access caches the app shell after first visit and keeps cached content within {html(META['cache_limit_mb'])} MB.
{stats['registrations']} registrations tracked across {stats['batches']} batches.
"""
def render_services(state: dict[str, Any], jurisdiction: dict[str, Any]) -> str:
"""Render the Google Services status and integration dashboard."""
services = google_services_status()
rows = "".join(
f"""
{html(name.replace('_', ' ').title())}
{'Active' if info['configured'] else 'Offline'}
{html(info['description'])}
"""
for name, info in services.items()
)
active_count = sum(1 for info in services.values() if info["configured"])
total_count = len(services)
return f"""
Platform integrations
Google Services Dashboard
Integration status
{active_count} of {total_count} Google services are active.
Google service integration status
Service
Status
Description
{rows}
AI Assistant (Gemini)
{'Google Gemini API key is configured.' if GeminiService.configured() else 'Set GOOGLE_GEMINI_API_KEY for live AI Q&A. Using curated FAQ fallback.'}
Content Translation
{'Google Translate API key is configured.' if TranslateService.configured() else 'Set GOOGLE_TRANSLATE_API_KEY for live translation. Returning original text.'}
URL Safety Check (Safe Browsing)
Google OAuth
{'OAuth client configured.' if OAuthService.configured() else 'Set GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET for Google Sign-In.'}
Google Sign-In provides secure, passwordless authentication for persistent voter profiles.