#!/usr/bin/env python3
"""Static viewer for the Mesa major-repair review.

The page body is generated separately into data/reports/ so refreshing the
figures is a re-run of the builder, not an edit to this file. Sits behind the
same login as the rest of the site and reuses the gen_service page key, so
anyone who can already see service costs can see this.
"""
import cgi
import sys
import os

sys.path.insert(0, '/opt/ngon/apps')
from managers.auth_manager import AuthManager, generate_login_page_html

REPORT = '/opt/ngon/data/reports/mesa_repair_review.html'

form = cgi.FieldStorage()
auth = AuthManager('gen_service')
auth_required, should_exit, headers = auth.require_auth(form)

if should_exit:
    print("Content-Type: application/json")
    if headers:
        print(headers)
    print("")
    print('{"success": false, "error": "Authentication required"}' if auth_required
          else '{"success": true}')
    sys.exit(0)

if auth_required:
    print("Content-Type: text/html")
    print("Cache-Control: no-cache, no-store, must-revalidate")
    print("Expires: 0")
    print("")
    print(generate_login_page_html("Mesa Major-Repair Review"))
    sys.exit(0)

# The figures here are rebuilt into data/reports/ out of band, so a heuristically
# cached copy of this page shows stale repair numbers with no way for the reader
# to tell. The login path gets it too: a cached login form shown to someone who
# has since signed in elsewhere reads as a lost session.
print("Content-Type: text/html; charset=utf-8")
print("Cache-Control: no-cache, no-store, must-revalidate")
print("Expires: 0")
print("")
if os.path.exists(REPORT):
    with open(REPORT, encoding='utf-8') as fh:
        print(fh.read())
else:
    print("<p style='font-family:sans-serif'>Report not generated yet.</p>")
