#!/usr/bin/env python3
"""
GAC NextGen - Ramp/Ground Handling Audit Dashboard Generator
--------------------------------------------------------------
Adapted from Samsic's build_16.py audit dashboard, but re-worked for the
GAC NextGen BlueKanGo export (export id 108), which differs structurally:

  * One shared row schema covers 8 checklist types (sections), and
    `name_of_checklist` tells you which section is active for that entry:
        PH   - Passenger Handling
        BH   - Baggage Handling
        RH   - Ramp Handling
        GSE  - GSE (Ground Support Equipment)
        PB   - Pushback
        AO   - Aircraft Offload / Arrival
        OD   - Aircraft Onload / Departure
        SFAC - SFAC (Special/Freight?) checks
  * Answers are "Yes" / "Non" / "N/A" / "N/O" instead of "C-"/"NC-" codes.
  * Because only one section's columns are populated per row, we don't need
    to hardcode column ranges: we scan every column and classify any cell
    whose value is exactly one of Yes/Non/N/A/N/O as a "question answer".
    This is robust to the messy/duplicated column names in the export.

Usage:
    export BK_USERNAME="omar.sajid"
    export BK_PASSWORD="PassPass@73"
    python build_nextgen_dashboard.py
"""

import os
import sys
import re
import json
import time
import base64
import difflib
from datetime import datetime

import requests

from field_mapping import CHECKLIST_MAPPINGS, get_checklist_code, detect_checklist_type

# ==========================================
# CONFIGURATION
# ==========================================
BK_BASE_URL = "https://us.bluekango.com/gac_nextgen"
NEXTGEN_EXPORT_ID = 108
PAGE_LIMIT = 200
TOKEN_TIMEOUT = 300
DASHBOARD_OUTPUT_DIR = "./"

VALID_ANSWERS = {"Yes", "Non", "No", "N/A", "N/O"}
# Yes = Compliant, Non/No = Non-Compliant, N/A = Not Applicable, N/O = Not Observed
ANSWER_MAP = {"Yes": "C", "Non": "NC", "No": "NC", "N/A": "NA", "N/O": "NO"}

METADATA_KEYS = {
    "entry_no", "entry_date", "last_modification_date", "system_modification_date",
    "declaring_user", "status", "entity", "version_created_by", "version_created_on",
    "version", "auditor_inspector", "date", "name_of_checklist", "operator",
    "station", "airline", "flight_number", "aircraft_tail_registry",
    "aircraft_type", "gatestand",
}

# Each question is exported as a fixed group of 8 columns: the real answer,
# then 5 corrective-action-record sub-fields (trigger/creation-date/
# responsible/due-date/narrative), then remarks, then a photo. BlueKanGo
# truncates long column names to a fixed length, so those CAR sub-field
# names sometimes collide down to a bare "_2".."_6" suffix with no
# identifying substring left -- they can't be reliably filtered by name.
# But the group size is always exactly 8 columns, repeating until a
# "general_comments"/"name"/"signature" section-boundary column is hit, so
# position-based chunking is the robust way to isolate the true answer
# column (first of each chunk) for every checklist section.
SECTION_BOUNDARY_RE = re.compile(r"^(general_comments|name|signature)(_\d+)?$", re.IGNORECASE)
QUESTION_GROUP_SIZE = 8


def identify_answer_columns(header):
    """Walk the header in declared order and return the set of column names
    that are the true first-of-group answer columns for every section."""
    answer_cols = []
    i = 0
    n = len(header)
    while i < n and header[i] in METADATA_KEYS:
        i += 1
    while i < n:
        # one section: repeated 8-column question groups until we hit the
        # general_comments/name/signature boundary trio
        while i < n and not SECTION_BOUNDARY_RE.match(header[i]):
            answer_cols.append(header[i])
            i += QUESTION_GROUP_SIZE
        # skip the general_comments, name, signature boundary columns
        while i < n and SECTION_BOUNDARY_RE.match(header[i]):
            i += 1
    return set(answer_cols)


def get_credentials():
    username = "omar.sajid"
    password = "PassPass@73"
    if not username or not password:
        sys.exit("Missing credentials. Set BK_USERNAME and BK_PASSWORD environment variables.")
    return username, password


def get_token(username, password):
    print("Authenticating with BlueKanGo API...")
    auth_str = f"{username}:{password}"
    basic_auth = base64.b64encode(auth_str.encode()).decode()
    url = f"{BK_BASE_URL}/app/rest/login"
    resp = requests.get(
        url,
        headers={"Authorization": f"Basic {basic_auth}", "Accept": "application/json"},
        params={"timeout": TOKEN_TIMEOUT},
        timeout=30,
    )
    resp.raise_for_status()
    token = resp.json().get("data", {}).get("token")
    if not token:
        raise Exception("Failed to retrieve token.")
    return token


def fetch_data(token, export_id):
    print(f"Fetching entries from BlueKanGo export {export_id}...")
    headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
    records = []
    page = 1
    while True:
        url = f"{BK_BASE_URL}/app/rest/entries/export/{export_id}"
        resp = requests.get(url, headers=headers, params={"page": page, "limit": PAGE_LIMIT}, timeout=60)
        if not resp.ok:
            break
        payload = resp.json().get("data", [])
        if isinstance(payload, dict):
            payload = payload.get("entries", [])
        if not payload:
            break
        records.extend(payload)
        print(f"  fetched page {page}: {len(payload)} entries (total {len(records)})")
        if len(payload) < PAGE_LIMIT:
            break
        page += 1
        time.sleep(1)
    return records


def extract_val(val):
    """BlueKanGo often wraps scalar values in a single-element JSON list."""
    if isinstance(val, list):
        return str(val[0]).strip() if val else ""
    if val is None:
        return ""
    if isinstance(val, dict):
        return ""
    return str(val).strip()


def format_date(raw_date):
    if not raw_date:
        return None
    raw_str = str(raw_date).strip()
    if raw_str.isdigit() or (raw_str.startswith("-") and raw_str[1:].isdigit()):
        try:
            return datetime.fromtimestamp(int(raw_str)).strftime("%Y-%m-%d")
        except Exception:
            pass
    if re.match(r"^\d{4}-\d{2}-\d{2}", raw_str):
        return raw_str[:10]
    m = re.match(r"^(\d{2})/(\d{2})/(\d{4})", raw_str)
    if m:
        return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"
    return None


def get_form_code(raw_checklist_name):
    """Map the free-text name_of_checklist value to a short section code,
    using field_mapping.py's own checklist-name pattern detection so the
    code always aligns with CHECKLIST_MAPPINGS keys (e.g. 'AIRCRAFT ONLOAD /
    DEPARTURE (AD)' correctly maps to 'OD', not a mismatched 'AD')."""
    code = detect_checklist_type(raw_checklist_name)
    if code:
        return code
    raw = raw_checklist_name.strip()
    return raw[:8].upper() if raw else "OTHER"


def prettify_label(key):
    """Fallback: turn an ugly export column name into a readable-ish label,
    used only if no match is found in field_mapping.py at all."""
    label = key
    label = re.sub(r"^(nbsp)?\d+_?[a-z]{2,5}\.?_?", "", label, flags=re.IGNORECASE)
    label = label.replace("nbsp", " ").replace("_", " ").strip()
    label = re.sub(r"\s+", " ", label)
    if not label:
        label = key
    return label[:1].upper() + label[1:] if label else key


# Build an exact-match lookup (raw export column key -> real question text)
# straight from field_mapping.py, plus a per-section list of (key, label) for
# fuzzy fallback in case an export uses a slightly different truncation
# point than what's recorded in field_mapping.py.
_EXACT_LABELS = {}
_SECTION_ITEMS = {}
for _code, _section in CHECKLIST_MAPPINGS.items():
    _SECTION_ITEMS[_code] = _section["items"]
    for _key, _label in _section["items"]:
        _EXACT_LABELS[_key] = _label


def lookup_label(key):
    if key in _EXACT_LABELS:
        return _EXACT_LABELS[key]
    section_code = get_checklist_code(key)
    if section_code and section_code in _SECTION_ITEMS:
        candidate_keys = [k for k, _ in _SECTION_ITEMS[section_code]]
        close = difflib.get_close_matches(key, candidate_keys, n=1, cutoff=0.6)
        if close:
            for k, label in _SECTION_ITEMS[section_code]:
                if k == close[0]:
                    return label
    return prettify_label(key)


def process_entries(raw_records):
    formatted = []
    skipped = 0

    if not raw_records:
        return formatted

    header = list(raw_records[0].keys())
    answer_columns = identify_answer_columns(header)
    print(f"Identified {len(answer_columns)} real answer columns out of {len(header)} total columns.")

    for r in raw_records:
        status = extract_val(r.get("status", "")).upper()
        if "DELET" in status:
            skipped += 1
            continue

        raw_time = (
            extract_val(r.get("date"))
            or extract_val(r.get("entry_date"))
            or extract_val(r.get("system_modification_date"))
        )
        audit_date = format_date(raw_time)
        if not audit_date:
            skipped += 1
            continue
        year, month, _ = audit_date.split("-")

        checklist_raw = extract_val(r.get("name_of_checklist"))
        form_code = get_form_code(checklist_raw)

        station = extract_val(r.get("station")) or "Unknown"
        airline = extract_val(r.get("airline")) or "Unknown"
        operator = extract_val(r.get("operator")) or ""
        aircraft_type = extract_val(r.get("aircraft_type")) or ""
        auditor = extract_val(r.get("auditor_inspector")) or extract_val(r.get("declaring_user")) or "Unknown"
        entry_no = extract_val(r.get("entry_no")) or "N/A"

        qs = {}
        c_count = 0
        nc_count = 0
        na_count = 0
        no_count = 0
        answered_count = 0

        for key, val in r.items():
            if key not in answer_columns:
                continue
            ans = extract_val(val)
            if ans not in VALID_ANSWERS:
                continue
            status_type = ANSWER_MAP[ans]
            qs[key] = status_type
            answered_count += 1
            if status_type == "C":
                c_count += 1
            elif status_type == "NC":
                nc_count += 1
            elif status_type == "NA":
                na_count += 1
            elif status_type == "NO":
                no_count += 1

        if answered_count == 0:
            skipped += 1
            continue

        total_valid = c_count + nc_count
        compliance_pct = (c_count / total_valid * 100) if total_valid > 0 else 0
        # completion: how many questions got *any* answer (incl NA/NO) out of all answered
        completion_pct = 100.0 if answered_count > 0 else 0.0

        formatted.append({
            "audit_ref": f"{entry_no}_{form_code}",
            "audit_date": audit_date,
            "year_month": f"{year}-{month}",
            "station": station,
            "airline": airline,
            "operator": operator,
            "aircraft_type": aircraft_type,
            "auditor": auditor,
            "forms": form_code,
            "conformity": c_count,
            "non_conformity": nc_count,
            "not_applicable": na_count,
            "not_observed": no_count,
            "compliance_pct": round(compliance_pct, 1),
            "completion_pct": round(completion_pct, 1),
            "qs": qs,
        })

    formatted.sort(key=lambda x: x["audit_date"], reverse=True)
    print(f"Processed {len(formatted)} entries. (Skipped {skipped})")
    return formatted


def build_question_labels(all_audits):
    labels = {}
    for a in all_audits:
        for k in a["qs"].keys():
            if k not in labels:
                labels[k] = lookup_label(k)
    return labels


# ==========================================
# HTML / JS DASHBOARD TEMPLATE
# ==========================================
HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GAC NextGen Audit & Compliance</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  :root {
    --bg: #eef2f7; --surface: #ffffff; --surface2: #f4f7fb; --border: #dde3ec;
    --ink: #0e1c2b; --ink2: #344d63; --ink3: #6b83a0; --ink4: #a8bad0;
    --red: #cc2c2c; --amber: #b56d00; --green: #187f4c; --brand: #2b5c92; --brand-light: #eef4fb;
    --shadow: 0 4px 12px rgba(14, 28, 43, 0.03), 0 1px 3px rgba(14, 28, 43, 0.05);
  }
  body { font-family: 'Plus Jakarta Sans', sans-serif; background: var(--bg); color: var(--ink); font-size: 14px; -webkit-font-smoothing: antialiased; }

  .header { background: var(--surface); padding: 20px 32px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; z-index: 100; box-shadow: 0 1px 2px rgba(0,0,0,0.02); }
  .h-title { font-size: 20px; font-weight: 700; color: var(--ink); display: flex; align-items: center; gap: 12px; letter-spacing: -0.01em; }
  .h-icon {
  background: var(--brand-light);
  color: var(--brand);
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  font-size: 20px;

  /* Add these */
  overflow: hidden;
  flex-shrink: 0;
}

.h-icon img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}
  .h-meta { font-family: 'JetBrains Mono', monospace; font-size: 12px; color: var(--ink3); background: var(--surface2); padding: 6px 12px; border-radius: 6px; border: 1px solid var(--border); }

  .layout { display: flex; gap: 24px; max-width: 1700px; margin: 0 auto; padding: 24px 32px; align-items: flex-start; }

  .sidebar { width: 320px; flex-shrink: 0; display: flex; flex-direction: column; gap: 16px; position: sticky; top: 90px; max-height: calc(100vh - 120px); overflow-y: auto; padding-right: 8px; }
  .sidebar::-webkit-scrollbar { width: 6px; }
  .sidebar::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }

  .filter-sec { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 18px; box-shadow: var(--shadow); }
  .filter-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
  .filter-title { font-size: 12px; font-weight: 700; color: var(--ink); text-transform: uppercase; letter-spacing: 0.05em; }
  .filter-actions { display: flex; gap: 8px; }
  .filter-actions button { font-size: 10px; font-weight: 700; color: var(--brand); background: none; border: none; cursor: pointer; text-transform: uppercase; padding: 2px 4px; border-radius: 4px; }

  .filter-options { display: flex; flex-wrap: wrap; gap: 8px; }
  .filter-btn { padding: 8px 12px; border-radius: 8px; font-size: 12px; font-family: inherit; font-weight: 600; border: 1px solid var(--border); background: var(--surface2); color: var(--ink3); cursor: pointer; transition: 0.15s ease; user-select: none; }
  .filter-btn.active { background: var(--brand); color: white; border-color: var(--brand); box-shadow: 0 2px 6px rgba(43, 92, 146, 0.25); }

  .date-range { display: flex; flex-direction: column; gap: 12px; }
  .date-range div { display: flex; flex-direction: column; gap: 4px; }
  .date-range label { font-size: 11px; font-weight: 600; color: var(--ink3); text-transform: uppercase; letter-spacing: 0.05em; }
  .date-range input { font-family: 'Plus Jakarta Sans', sans-serif; font-size: 13px; color: var(--ink); padding: 10px 14px; border: 1px solid var(--border); border-radius: 8px; outline: none; background: var(--surface2); }

  .btn-reset { width: 100%; padding: 12px; background: var(--surface2); border: 1px solid var(--border); border-radius: 8px; color: var(--ink2); font-weight: 700; font-size: 12px; cursor: pointer; transition: 0.2s; text-transform: uppercase; letter-spacing: 0.05em; display: flex; align-items: center; justify-content: center; gap: 8px; }

  .main-content { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 24px; }
  .kpi-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
  .kpi-card { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 20px; box-shadow: var(--shadow); position: relative; overflow: hidden; }
  .kpi-card::before { content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 4px; border-radius: 4px 0 0 4px; }
  .kpi-card.c-brand::before { background: var(--brand); } .kpi-card.c-green::before { background: var(--green); } .kpi-card.c-amber::before { background: var(--amber); }
  .kpi-title { font-size: 12px; font-weight: 600; color: var(--ink3); margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.03em; }
  .kpi-val { font-size: 32px; font-weight: 800; color: var(--ink); line-height: 1; letter-spacing: -0.02em; }
  .kpi-sub { font-size: 12px; color: var(--ink3); margin-top: 6px; font-weight: 500; }

  .charts-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; }
  .card { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 24px; box-shadow: var(--shadow); display: flex; flex-direction: column; }
  .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
  .card-title { font-size: 15px; font-weight: 700; color: var(--ink); }
  .chart-wrap { position: relative; height: 260px; width: 100%; flex-grow: 1; }

  .table-wrap { overflow-x: auto; max-height: 400px; overflow-y: auto; border: 1px solid var(--border); border-radius: 8px; }
  table { width: 100%; border-collapse: separate; border-spacing: 0; text-align: left; }
  th { background: var(--surface2); padding: 12px 16px; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; color: var(--ink3); position: sticky; top: 0; z-index: 10; border-bottom: 1px solid var(--border); }
  td { padding: 14px 16px; border-bottom: 1px solid var(--border); font-size: 13.5px; color: var(--ink2); font-weight: 500; }
  tr:last-child td { border-bottom: none; }
  tr:hover td { background: var(--surface2); }
  .td-no { font-family: 'JetBrains Mono', monospace; font-size: 12px; color: var(--ink4); }
  .td-dt { font-family: 'JetBrains Mono', monospace; font-size: 13px; color: var(--ink); }
</style>
</head>
<body>

<div class="header">
  <div class="h-title">
    <div class="h-icon">
      <img src="nextgen.png" alt="NextGen Logo">
    </div>
    <span>NextGen Audit &amp; Compliance (1.6)</span>
  </div>
  <div class="h-meta">Last Updated: /*__DATE__*/</div>
</div>

<div class="layout">
  <div class="sidebar">
    <button class="btn-reset" onclick="globalReset()">Reset Filters</button>
    <div class="filter-sec">
      <div class="filter-head"><div class="filter-title">Date Range</div></div>
      <div class="date-range">
        <div><label>From</label><input type="month" id="f-from" onchange="updateUI()"></div>
        <div><label>To</label><input type="month" id="f-to" onchange="updateUI()"></div>
      </div>
    </div>
    <div class="filter-sec">
      <div class="filter-head">
        <div class="filter-title">Checklist Section</div>
        <div class="filter-actions"><button onclick="toggleAll('f-forms', true)">All</button><button onclick="toggleAll('f-forms', false)">None</button></div>
      </div>
      <div class="filter-options" id="f-forms"></div>
    </div>
    <div class="filter-sec">
      <div class="filter-head">
        <div class="filter-title">Station</div>
        <div class="filter-actions"><button onclick="toggleAll('f-st', true)">All</button><button onclick="toggleAll('f-st', false)">None</button></div>
      </div>
      <div class="filter-options" id="f-st"></div>
    </div>
    <div class="filter-sec">
      <div class="filter-head">
        <div class="filter-title">Airline</div>
        <div class="filter-actions"><button onclick="toggleAll('f-air', true)">All</button><button onclick="toggleAll('f-air', false)">None</button></div>
      </div>
      <div class="filter-options" id="f-air"></div>
    </div>
  </div>

  <div class="main-content">
    <div class="kpi-grid">
      <div class="kpi-card c-brand"><div class="kpi-title">Total Audits</div><div class="kpi-val" id="kpi-total">-</div><div class="kpi-sub">Filtered count</div></div>
      <div class="kpi-card c-green"><div class="kpi-title">Global Compliance</div><div class="kpi-val" id="kpi-comp">-</div><div class="kpi-sub">Average Pass Rate</div></div>
      <div class="kpi-card c-amber"><div class="kpi-title">Checklist Completion</div><div class="kpi-val" id="kpi-done">-</div><div class="kpi-sub">Average Fields Answered</div></div>
    </div>

    <div class="charts-grid">
      <div class="card">
        <div class="card-header"><div class="card-title">Station Distribution</div></div>
        <div class="chart-wrap"><canvas id="ch-stdist"></canvas></div>
      </div>
      <div class="card">
        <div class="card-header"><div class="card-title">Airline Distribution</div></div>
        <div class="chart-wrap"><canvas id="ch-airdist"></canvas></div>
      </div>

      <div class="card">
        <div class="card-header"><div class="card-title">Best &amp; Worst Stations Trend (%)</div></div>
        <div class="chart-wrap"><canvas id="ch-st-trend"></canvas></div>
      </div>
      <div class="card">
        <div class="card-header"><div class="card-title">Best &amp; Worst Airlines Trend (%)</div></div>
        <div class="chart-wrap"><canvas id="ch-air-trend"></canvas></div>
      </div>

      <div class="card" style="grid-column: 1 / span 2;">
        <div class="card-header"><div class="card-title">Compliance by Checklist Section</div></div>
        <div class="chart-wrap"><canvas id="ch-chkcomp"></canvas></div>
      </div>

      <div class="card" style="grid-column: 1 / span 2;">
        <div class="card-header" style="border-bottom: 1px solid var(--border); padding-bottom: 16px;">
          <div class="card-title">Question Compliance Overview</div>
          <div style="display:flex; align-items:center; gap:8px;">
            <span style="font-size:12px; font-weight:600; color:var(--ink3)">Show Top/Bottom N:</span>
            <select id="sel-topn" onchange="updateUI()" style="padding:4px 8px; border:1px solid var(--border); border-radius:6px; background:var(--surface2); color:var(--ink); outline:none;">
              <option value="5">Top &amp; Bottom 5</option>
              <option value="10">Top &amp; Bottom 10</option>
              <option value="25">Top &amp; Bottom 25</option>
            </select>
          </div>
        </div>
        <div style="display: flex; gap: 24px; padding-top: 16px;">
            <div style="flex: 1; min-width: 0;">
                <div style="font-size:13px; font-weight:600; text-align:center; margin-bottom:12px;">Top Compliant Questions</div>
                <div class="chart-wrap" style="height:350px; flex-grow:0; overflow:hidden"><canvas id="ch-qcomp-top"></canvas></div>
            </div>
            <div style="flex: 1; min-width: 0;">
                <div style="font-size:13px; font-weight:600; text-align:center; margin-bottom:12px;">Least Compliant Questions</div>
                <div class="chart-wrap" style="height:350px; flex-grow:0; overflow:hidden"><canvas id="ch-qcomp-bot"></canvas></div>
            </div>
        </div>
      </div>

      <div class="card" style="grid-column: 1 / span 2;">
        <div class="card-header"><div class="card-title">C / NC / N-O / N-A by Question (Stacked)</div></div>
        <div id="qstack-legend" style="display:flex; gap:8px; flex-wrap:wrap; margin-bottom:14px;"></div>
        <div class="chart-wrap" style="height:400px"><canvas id="ch-qstack"></canvas></div>
      </div>
    </div>

    <div class="card" style="padding:0; overflow:hidden">
      <div class="card-header" style="padding:24px 24px 0 24px; margin-bottom:16px;">
        <div class="card-title">Detailed Audit Log</div>
      </div>
      <div class="table-wrap" style="border:none; border-top:1px solid var(--border); border-radius:0;">
        <table>
          <thead><tr>
            <th>Entry Ref</th><th>Date</th><th>Section</th>
            <th>Station</th><th>Airline</th><th>Auditor</th>
            <th>Compliance %</th>
          </tr></thead>
          <tbody id="t-body"></tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<script>
let charts = {};
/*__INJECT_AUDITS__*/
/*__INJECT_LABELS__*/

function getUnique(key) {
    const s = new Set();
    AUDITS.forEach(a => { if(a[key]) s.add(a[key]); });
    return Array.from(s).sort();
}

let filters = { forms: new Set(), station: new Set(), airline: new Set() };
let fAud = [];

function init() {
    ['forms', 'station', 'airline'].forEach(k => {
        const u = getUnique(k);
        filters[k] = new Set(u);
        const html = u.map(v => `<div class="filter-btn active" data-key="${k}" data-val="${v}" onclick="toggleF(this)">${v}</div>`).join('');
        document.getElementById(`f-${k === 'station' ? 'st' : k === 'airline' ? 'air' : k}`).innerHTML = html;
    });
    updateUI();
}

function toggleF(el) {
    const k = el.getAttribute('data-key');
    const v = el.getAttribute('data-val');
    if(filters[k].has(v)) { filters[k].delete(v); el.classList.remove('active'); }
    else { filters[k].add(v); el.classList.add('active'); }
    updateUI();
}

function toggleAll(id, state) {
    const key = id === 'f-st' ? 'station' : id === 'f-air' ? 'airline' : 'forms';
    document.getElementById(id).querySelectorAll('.filter-btn').forEach(el => {
        const v = el.getAttribute('data-val');
        if(state) { filters[key].add(v); el.classList.add('active'); }
        else { filters[key].delete(v); el.classList.remove('active'); }
    });
    updateUI();
}

function globalReset() {
    document.getElementById('f-from').value = '';
    document.getElementById('f-to').value = '';
    ['f-forms', 'f-st', 'f-air'].forEach(id => toggleAll(id, true));
}

function updateUI() {
    const dFrom = document.getElementById('f-from').value;
    const dTo = document.getElementById('f-to').value;

    fAud = AUDITS.filter(a => {
        if(!a.station || a.station === 'Unknown' || !a.airline || a.airline === 'Unknown') return false;
        if(dFrom && a.year_month < dFrom) return false;
        if(dTo && a.year_month > dTo) return false;
        if(!filters.station.has(a.station)) return false;
        if(!filters.airline.has(a.airline)) return false;
        return filters.forms.has(a.forms);
    });

    let tc=0, tn=0;
    fAud.forEach(a => { tc+=a.conformity; tn+=a.non_conformity; });

    document.getElementById('kpi-total').innerText = fAud.length;
    document.getElementById('kpi-comp').innerText = (tc+tn)>0 ? (tc/(tc+tn)*100).toFixed(1)+'%' : '-';
    document.getElementById('kpi-done').innerText = fAud.length ? (fAud.reduce((s,a)=>s+a.completion_pct,0)/fAud.length).toFixed(1)+'%' : '-';

    renderCharts();
    renderTable();
}

function wrapTooltip(text) {
    const words = text.split(' ');
    let lines = [];
    let currentLine = words[0] || '';
    for (let i = 1; i < words.length; i++) {
        if (currentLine.length + words[i].length < 60) { currentLine += " " + words[i]; }
        else { lines.push(currentLine); currentLine = words[i]; }
    }
    lines.push(currentLine);
    return lines;
}

function renderCharts() {
    const allMonths = [...new Set(fAud.map(a=>a.year_month))].sort();
    const months = allMonths.slice(-12);
    const bgColors = ['#2b5c92', '#187f4c', '#cc2c2c', '#b56d00', '#6b83a0', '#344d63', '#a8bad0', '#81c784', '#e57373', '#64b5f6'];

    const stMap = {}; const airMap = {};
    fAud.forEach(a => {
        stMap[a.station] = (stMap[a.station]||0)+1;
        airMap[a.airline] = (airMap[a.airline]||0)+1;
    });

    if(charts['ch-stdist']) charts['ch-stdist'].destroy();
    charts['ch-stdist'] = new Chart(document.getElementById('ch-stdist'), {
        type: 'pie',
        data: { labels: Object.keys(stMap), datasets: [{ data: Object.values(stMap), backgroundColor: bgColors }] },
        options: { responsive:true, maintainAspectRatio:false, plugins: { legend: {position:'right'} } }
    });

    if(charts['ch-airdist']) charts['ch-airdist'].destroy();
    charts['ch-airdist'] = new Chart(document.getElementById('ch-airdist'), {
        type: 'pie',
        data: { labels: Object.keys(airMap), datasets: [{ data: Object.values(airMap), backgroundColor: bgColors }] },
        options: { responsive:true, maintainAspectRatio:false, plugins: { legend: {position:'right'} } }
    });

    const computeYAxisMin = (datasetsArr) => {
        let lowest = 100;
        datasetsArr.forEach(ds => { ds.data.forEach(v => { if(v !== null && v !== undefined && v < lowest) lowest = v; }); });
        if(lowest === 100) return 0;
        return Math.max(0, Math.floor(lowest - 5));
    };

    const processAllTrends = (key) => {
        const totals = {}; const monthly = {};
        fAud.forEach(a => {
            const v = a[key];
            if(!totals[v]) totals[v] = {c:0, t:0};
            totals[v].c += a.conformity; totals[v].t += (a.conformity + a.non_conformity);
            if(!monthly[a.year_month]) monthly[a.year_month] = {};
            if(!monthly[a.year_month][v]) monthly[a.year_month][v] = {c:0, t:0};
            monthly[a.year_month][v].c += a.conformity;
            monthly[a.year_month][v].t += (a.conformity + a.non_conformity);
        });
        const allKeys = Object.keys(totals).sort();
        return allKeys.map((k, i) => {
            const data = months.map(m => { const s = monthly[m]?.[k]; return s && s.t>0 ? (s.c/s.t)*100 : null; });
            return { label: k, data, borderColor: bgColors[i % bgColors.length], backgroundColor: bgColors[i % bgColors.length], spanGaps: true, fill: false, tension: 0.2 };
        });
    };

    const stDatasets = processAllTrends('station');
    if(charts['ch-st-trend']) charts['ch-st-trend'].destroy();
    charts['ch-st-trend'] = new Chart(document.getElementById('ch-st-trend'), {
        type: 'line',
        data: { labels: months, datasets: stDatasets },
        options: { responsive:true, maintainAspectRatio:false, plugins: { legend: {display:false} }, scales:{y:{min:computeYAxisMin(stDatasets),max:100}} }
    });

    const airDatasets = processAllTrends('airline');
    if(charts['ch-air-trend']) charts['ch-air-trend'].destroy();
    charts['ch-air-trend'] = new Chart(document.getElementById('ch-air-trend'), {
        type: 'line',
        data: { labels: months, datasets: airDatasets },
        options: { responsive:true, maintainAspectRatio:false, plugins: { legend: {display:false} }, scales:{y:{min:computeYAxisMin(airDatasets),max:100}} }
    });

    // Compliance by checklist section (PH/BH/RH/GSE/PB/AO/OD/SFAC)
    const chkMap = {};
    fAud.forEach(a => {
        if(!filters.forms.has(a.forms)) return;
        if(!chkMap[a.forms]) chkMap[a.forms] = {C:0, NC:0};
        chkMap[a.forms].C += a.conformity;
        chkMap[a.forms].NC += a.non_conformity;
    });
    const chkLabels = Object.keys(chkMap).sort();
    const chkData = chkLabels.map(k => { const t = chkMap[k].C + chkMap[k].NC; return t > 0 ? (chkMap[k].C/t)*100 : 0; });

    if(charts['ch-chkcomp']) charts['ch-chkcomp'].destroy();
    charts['ch-chkcomp'] = new Chart(document.getElementById('ch-chkcomp'), {
        type: 'bar',
        data: { labels: chkLabels, datasets: [{ data: chkData, backgroundColor: '#2b5c92' }] },
        options: { responsive:true, maintainAspectRatio:false, plugins: { legend: {display:false} }, scales:{y:{min:0,max:100}} }
    });

    // Question-level compliance (only across active section filters)
    const qMap = {};
    fAud.forEach(a => {
        if(!a.qs) return;
        if(!filters.forms.has(a.forms)) return;
        Object.entries(a.qs).forEach(([k, val]) => {
            if(!qMap[k]) qMap[k] = {C:0, NC:0, NA:0, NO:0};
            if(qMap[k][val] !== undefined) qMap[k][val]++;
        });
    });

    let qArr = Object.keys(qMap).map(k => {
        const C = qMap[k].C, NC = qMap[k].NC, NA = qMap[k].NA, NO = qMap[k].NO;
        const comp = (C+NC) > 0 ? (C/(C+NC))*100 : 0;
        const fullText = QLABELS[k] || k;
        const shortLabel = fullText.length > 40 ? fullText.slice(0, 37) + '...' : fullText;
        return { shortLabel, fullText, k, C, NC, NA, NO, comp, total: C+NC+NA+NO };
    }).filter(q => q.total > 0);

    qArr.sort((a, b) => b.comp - a.comp);
    const n = parseInt(document.getElementById('sel-topn').value, 10);
    const topQ = qArr.slice(0, n);
    const botQ = qArr.slice(-n).reverse();

    if(charts['ch-qcomp-top']) charts['ch-qcomp-top'].destroy();
    charts['ch-qcomp-top'] = new Chart(document.getElementById('ch-qcomp-top'), {
        type: 'bar',
        data: { labels: topQ.map(q=>q.shortLabel), datasets: [{ data: topQ.map(q=>q.comp), backgroundColor: '#81c784', barThickness: 20 }] },
        options: {
            responsive:true, maintainAspectRatio:false, indexAxis: 'y',
            plugins: { legend: {display:false}, tooltip: { callbacks: {
                title: (ctx) => wrapTooltip(topQ[ctx[0].dataIndex].fullText),
                label: ctx => ` Compliance: ${ctx.parsed.x.toFixed(2)}%`
            } } },
            scales:{x:{min:0,max:100}, y:{ticks:{autoSkip:false}}}
        }
    });

    if(charts['ch-qcomp-bot']) charts['ch-qcomp-bot'].destroy();
    charts['ch-qcomp-bot'] = new Chart(document.getElementById('ch-qcomp-bot'), {
        type: 'bar',
        data: { labels: botQ.map(q=>q.shortLabel), datasets: [{ data: botQ.map(q=>q.comp), backgroundColor: '#e57373', barThickness: 20 }] },
        options: {
            responsive:true, maintainAspectRatio:false, indexAxis: 'y',
            plugins: { legend: {display:false}, tooltip: { callbacks: {
                title: (ctx) => wrapTooltip(botQ[ctx[0].dataIndex].fullText),
                label: ctx => ` Compliance: ${ctx.parsed.x.toFixed(1)}%`
            } } },
            scales:{x:{min:0,max:100}, y:{ticks:{autoSkip:false}}}
        }
    });

    // Stacked C/NC/NO/NA by question
    const qArrStack = [...qArr].sort((a,b) => a.k.localeCompare(b.k));
    const qLabels = qArrStack.map(q => q.shortLabel);
    const stackDatasets = [
        { label: 'C',  data: qArrStack.map(q=>q.C),  backgroundColor: '#81c784' },
        { label: 'NC', data: qArrStack.map(q=>q.NC), backgroundColor: '#e57373' },
        { label: 'N-O', data: qArrStack.map(q=>q.NO), backgroundColor: '#64b5f6' },
        { label: 'N-A', data: qArrStack.map(q=>q.NA), backgroundColor: '#bdbdbd' }
    ];

    if(charts['ch-qstack']) charts['ch-qstack'].destroy();
    charts['ch-qstack'] = new Chart(document.getElementById('ch-qstack'), {
        type: 'bar',
        data: { labels: qLabels, datasets: stackDatasets },
        options: {
            responsive:true, maintainAspectRatio:false, indexAxis: 'y',
            plugins: { legend: { display: false }, tooltip: { callbacks: {
                title: (ctx) => wrapTooltip(qArrStack[ctx[0].dataIndex].fullText)
            } } },
            scales: { x: { stacked: true }, y: { stacked: true } }
        }
    });

    const legendDiv = document.getElementById('qstack-legend');
    legendDiv.innerHTML = '';
    stackDatasets.forEach((ds, i) => {
        const btn = document.createElement('button');
        btn.style.cssText = `border: 2px solid ${ds.backgroundColor}; color: ${ds.backgroundColor}; background: transparent; border-radius: 6px; padding: 5px 14px; font-size: 12px; font-weight: 700; cursor: pointer; transition: background 0.15s, color 0.15s; font-family: inherit; letter-spacing: 0.03em;`;
        btn.textContent = ds.label;
        btn.title = ds.label === 'C' ? 'Compliant' : ds.label === 'NC' ? 'Non-Compliant' : ds.label === 'N-O' ? 'Not Observed' : 'Not Applicable';
        btn.addEventListener('mouseenter', () => { if(!btn.dataset.hidden) btn.style.background = ds.backgroundColor + '22'; });
        btn.addEventListener('mouseleave', () => { if(!btn.dataset.hidden) btn.style.background = 'transparent'; });
        btn.addEventListener('click', () => {
            const meta = charts['ch-qstack'].getDatasetMeta(i);
            meta.hidden = !meta.hidden;
            btn.dataset.hidden = meta.hidden ? '1' : '';
            btn.style.opacity = meta.hidden ? '0.35' : '1';
            btn.style.background = 'transparent';
            charts['ch-qstack'].update();
        });
        legendDiv.appendChild(btn);
    });
}

function renderTable(){
  const tb = document.getElementById('t-body');
  if(!fAud.length){ tb.innerHTML=`<tr><td colspan="7" style="text-align:center;padding:30px;color:var(--ink4)">No audits match filters</td></tr>`; return; }
  tb.innerHTML = fAud.map(a => `<tr>
    <td class="td-dt">${a.audit_ref}</td><td class="td-no">${a.audit_date}</td>
    <td><strong>${a.forms}</strong></td><td>${a.station}</td><td>${a.airline}</td><td>${a.auditor}</td>
    <td><span style="color:${a.compliance_pct>=80?'var(--green)':'var(--red)'}; font-weight:700">${a.compliance_pct}%</span></td>
  </tr>`).join('');
}

init();
</script>
</body>
</html>
"""


def run():
    print("Starting GAC NextGen Audit Dashboard Generation...")
    username, password = get_credentials()
    token = get_token(username, password)

    raw_entries = fetch_data(token, NEXTGEN_EXPORT_ID)
    processed = process_entries(raw_entries)
    question_labels = build_question_labels(processed)

    last_updated_str = datetime.now().strftime("%b %d, %Y, %H:%M")

    html_output = HTML_TEMPLATE.replace(
        "/*__INJECT_AUDITS__*/", f"AUDITS = {json.dumps(processed)};"
    )
    html_output = html_output.replace(
        "/*__INJECT_LABELS__*/", f"const QLABELS = {json.dumps(question_labels)};"
    )
    html_output = html_output.replace("/*__DATE__*/", last_updated_str)

    os.makedirs(DASHBOARD_OUTPUT_DIR, exist_ok=True)
    out_path = os.path.join(DASHBOARD_OUTPUT_DIR, "nextgen_16_dashboard.html")
    with open(out_path, "w", encoding="utf-8") as f:
        f.write(html_output)

    print(f"Dashboard generated successfully at: {out_path}")


if __name__ == "__main__":
    run()