#!/usr/bin/env python3
import pyodbc
import os
import json
import getpass

# ---------------------------------------------------------
# CONFIGURATION
# ---------------------------------------------------------

SERVER = r"BRAVO\SQLEXPRESS01"
DATABASE = "cresql"
HTML_OUTPUT = r"C:\Temp\pcAmerica\HTML\tables.html"

CONN_STR = (
    "DRIVER={ODBC Driver 17 for SQL Server};"
    f"SERVER={SERVER};"
    f"DATABASE={DATABASE};"
    "Trusted_Connection=yes;"
)

# ---------------------------------------------------------
# GROUP → USERS
# ---------------------------------------------------------

GROUPS = {
    "Admin": ["michael", "susan", "david"],
    "Accounting": ["jane", "robert"],
    "IT": ["michael", "alex", "steve"],
    "Sales": ["linda", "john", "kevin"],
    "Support": ["nancy", "omar"]
}

# ---------------------------------------------------------
# GROUP → TABLE PERMISSIONS
# ---------------------------------------------------------

GROUP_TABLE_ACCESS = {
    "Admin": "*",
    "Accounting": ["Invoices", "Payments", "Vendors"],
    "IT": ["Technology", "Servers", "Logs", "Users"],
    "Sales": ["Orders", "Customers", "Quotes"],
    "Support": ["Tickets", "Customers"]
}

# ---------------------------------------------------------
# MAIN FUNCTION
# ---------------------------------------------------------

def generate_table_list_html():
    logged_in_user = getpass.getuser().lower()

    # Determine user's group
    user_group = None
    for group, users in GROUPS.items():
        if logged_in_user in [u.lower() for u in users]:
            user_group = group
            break

    if not user_group:
        user_group = "Support"

    # Connect to SQL Server
    conn = pyodbc.connect(CONN_STR)
    cursor = conn.cursor()

    cursor.execute("""
        SELECT TABLE_NAME
        FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_TYPE = 'BASE TABLE'
        ORDER BY TABLE_NAME;
    """)

    all_tables = [row.TABLE_NAME for row in cursor.fetchall()]

    # Filter tables based on group permissions
    if GROUP_TABLE_ACCESS.get(user_group) == "*":
        allowed_tables = all_tables
    else:
        allowed_tables = [
            t for t in all_tables
            if t in GROUP_TABLE_ACCESS.get(user_group, [])
        ]

    # ---------------------------------------------------------
    # BUILD HTML (RAW F‑STRING)
    # ---------------------------------------------------------

    html = rf"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>cresql Database Tables</title>

<style>
body {{ font-family: Arial; background:#f4f4f4; padding:20px; }}

.banner {{
    width: 100%;
    background: #2b2b2b;
    color: #f2f2f2;
    padding: 25px;
    margin-bottom: 25px;
    border-radius: 6px;
    border: 1px solid #444;
}}

.banner h2 {{
    margin-top: 0;
    color: #ffffff;
}}

table {{ border-collapse: collapse; width: 100%; background:#fff; }}
th, td {{ border:1px solid #444; padding:8px; vertical-align: top; }}
th {{ background:#2b6cb0; color:white; }}
select {{ padding:6px; }}
textarea {{ width: 98%; height: 60px; resize: vertical; }}
button {{ padding:10px 16px; background:#2b6cb0; color:white; border:none; cursor:pointer; }}
button:hover {{ background:#1d4ed8; }}
.box {{ background:#fff; padding:15px; border:1px solid #ccc; margin-bottom:20px; }}
.readonly {{ background:#eee; color:#555; }}
</style>

<script>
const GROUP_DATA = {json.dumps(GROUPS)};
const LOGGED_IN_USER = "{logged_in_user}";
const USER_GROUP = "{user_group}";

function loadSettings() {{
    document.querySelectorAll("tr[data-table]").forEach(row => {{
        const table = row.dataset.table;

        const savedGroup = localStorage.getItem("group_" + table);
        const groupSelect = row.querySelector(".groupSelect");
        if (savedGroup && USER_GROUP === "Admin" && groupSelect) {{
            groupSelect.value = savedGroup;
        }}

        if (groupSelect) updateUsers(groupSelect, table, false);

        const savedUser = localStorage.getItem("user_" + table);
        const userSelect = row.querySelector(".userSelect");
        if (savedUser && userSelect) {{
            userSelect.value = savedUser;
        }}

        if (userSelect) {{
            const notes = localStorage.getItem("notes_" + table + "_" + userSelect.value) || "";
            row.querySelector(".notesEditable").value = notes;
        }}

        updateReadOnlyNotes(table);

        const msgBox = row.querySelector(".messagesBox");
        if (msgBox) {{
            const savedMsg = localStorage.getItem("messages_" + table);
            if (savedMsg) msgBox.value = savedMsg;
        }}
    }});
}}

function updateUsers(selectElem, table, resetUser = true) {{
    const group = selectElem.value;
    const users = GROUP_DATA[group] || [];

    const row = document.querySelector("tr[data-table='" + table + "']");
    const userSelect = row.querySelector(".userSelect");

    userSelect.innerHTML = users
        .map(u => `<option value="${{u}}">${{u}}</option>`)
        .join("");

    if (resetUser && users.length > 0) {{
        userSelect.value = users[0];
    }}

    loadNotesForUser(table, userSelect.value);
    updateReadOnlyNotes(table);
}}

function changeUser(selectElem, table) {{
    const user = selectElem.value;
    localStorage.setItem("user_" + table, user);
    loadNotesForUser(table, user);
    updateReadOnlyNotes(table);
}}

function loadNotesForUser(table, user) {{
    const notes = localStorage.getItem("notes_" + table + "_" + user) || "";
    document.querySelector("tr[data-table='" + table + "'] .notesEditable").value = notes;
}}

function generateAutoNote(table, user) {{
    const samples = [
        `Reviewed ${{table}}; no issues found.`,
        `${{table}} structure looks stable.`,
        `User ${{user}} has not added notes yet.`,
        `Awaiting review for ${{table}}.`,
        `No anomalies detected in ${{table}}.`,
        `Pending validation for ${{table}}.`,
        `Initial scan of ${{table}} completed.`,
        `No data integrity issues found in ${{table}}.`,
        `${{user}} has not documented findings for ${{table}}.`,
        `Table ${{table}} appears consistent with schema.`
    ];
    return samples[Math.floor(Math.random() * samples.length)];
}}

function updateReadOnlyNotes(table) {{
    const row = document.querySelector("tr[data-table='" + table + "']");
    const selectedUser = row.querySelector(".userSelect").value;

    let html = "";

    Object.values(GROUP_DATA).flat().forEach(u => {{
        if (u !== selectedUser) {{
            let notes = localStorage.getItem("notes_" + table + "_" + u);

            if (!notes || notes.trim() === "") {{
                notes = generateAutoNote(table, u);
                localStorage.setItem("notes_" + table + "_" + u, notes);
            }}

            html += `<strong>${{u}}:</strong><br>
                     <textarea class='readonly' readonly>${{notes}}</textarea><br>`;
        }}
    }});

    row.querySelector(".notesReadonly").innerHTML = html;
}}

function saveSettings() {{
    document.querySelectorAll("tr[data-table]").forEach(row => {{
        const table = row.dataset.table;

        const groupSelect = row.querySelector(".groupSelect");
        if (USER_GROUP === "Admin" && groupSelect) {{
            localStorage.setItem("group_" + table, groupSelect.value);
        }}

        const userSelect = row.querySelector(".userSelect");
        if (userSelect) {{
            const user = userSelect.value;
            localStorage.setItem("user_" + table, user);

            const notes = row.querySelector(".notesEditable").value;
            localStorage.setItem("notes_" + table + "_" + user, notes);
        }}

        const msgBox = row.querySelector(".messagesBox");
        if (msgBox) {{
            localStorage.setItem("messages_" + table, msgBox.value);
        }}
    }});

    alert("Settings saved.");
}}

function createNewEntry() {{
    const table = document.getElementById("newTable").value;
    const user = document.getElementById("newUser").value;
    const notes = document.getElementById("newNotes").value;

    localStorage.setItem("user_" + table, user);
    localStorage.setItem("notes_" + table + "_" + user, notes);

    alert("Entry saved.");
}}
</script>

</head>
<body onload="loadSettings()">

<div class="banner">
    <h2>cresql Database Overview</h2>

    <p><strong>Database File Locations:</strong><br>
       C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS01\MSSQL\DATA\cresql.mdf<br>
       C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS01\MSSQL\DATA\cresql_log.ldf
    </p>

    <p>
        The <strong>cresql</strong> database is the primary SQL Server data store used by 
        pcAmerica CRE (Cash Register Express). The MDF file contains all structured 
        relational data for the POS system, including inventory, items, transactions, 
        customers, employees, discounts, tax rules, and configuration metadata. The LDF 
        file stores SQL Server’s transaction log, enabling rollback, crash recovery, and 
        full ACID‑compliant write operations.
    </p>

    <p>
        pcAmerica CRE is a Windows‑based retail and restaurant point‑of‑sale platform 
        designed for high‑volume checkout environments. It uses SQL Server Express as its 
        backend engine, with all POS terminals reading and writing directly to the 
        <strong>cresql</strong> database. This makes the database the authoritative source 
        of truth for all sales, inventory, and operational activity.
    </p>

    <p>
        This page provides a structured view of the <strong>cresql</strong> database tables, 
        including user‑specific notes, cross‑user annotations, and administrative grouping 
        to support consultants, technicians, and analysts working with pcAmerica CRE.
    </p>

    <h2>Remote Script Access</h2>
    <p>
        The following endpoint provides direct access to the Python automation script 
        used for generating this table‑analysis interface:
        <br>
        <a href="https://delacruz.belliniseven.ai/PY/getTableList.py" 
           style="color:#9ecbff; text-decoration:none;">
           https://delacruz.belliniseven.ai/PY/getTableList.py
        </a>
    </p>

    <h2>Technical Summary of getTableList.py</h2>
    <p>
        The <strong>getTableList.py</strong> script connects to the SQL Server instance hosting 
        the <strong>cresql</strong> database and dynamically enumerates all base tables using 
        <em>INFORMATION_SCHEMA.TABLES</em>. It applies group‑based access control to filter 
        which tables are visible to the current Windows user, then generates a complete 
        HTML interface that includes:
    </p>

    <ul>
        <li>User‑selectable table ownership and grouping</li>
        <li>Editable per‑user notes stored in browser localStorage</li>
        <li>Auto‑generated AI‑style notes for all other users</li>
        <li>Shared message fields for cross‑team communication</li>
        <li>Dynamic user lists based on group membership</li>
        <li>Client‑side rendering of read‑only vs editable notes</li>
    </ul>

    <p>
        The script outputs a fully self‑contained HTML dashboard that requires no server‑side 
        components beyond the initial SQL query. All user‑specific data (notes, messages, 
        group selections) is stored locally in the browser, making the interface safe to use 
        across multiple consultants without modifying the underlying database.
    </p>
</div>

<h1>cresql Database Tables</h1>

<div class="box">
    <h3>Create New Entry</h3>
    <label>Table:</label>
    <select id="newTable">
        {''.join(f'<option value="{t}">{t}</option>' for t in allowed_tables)}
    </select>

    <label>User:</label>
    <select id="newUser">
        {''.join(f'<option value="{u}">{u}</option>' for u in GROUPS[user_group])}
    </select>

    <br><br>
    <textarea id="newNotes" placeholder="Enter notes..."></textarea>
    <br><br>
    <button onclick="createNewEntry()">Save New Entry</button>
</div>

<button onclick="saveSettings()">Save Settings</button>
<br><br>

<table>
<tr>
    <th>Table Name</th>
    <th>Group</th>
    <th>User</th>
    <th>Editable Notes</th>
    <th>Other Users' Notes</th>
    <th>Messages</th>
</tr>
"""

    # ---------------------------------------------------------
    # TABLE ROWS
    # ---------------------------------------------------------

    for table in allowed_tables:
        if user_group == "Admin":
            group_cell = (
                f"<select class='groupSelect' "
                f"onchange=\"updateUsers(this, '{table}', true)\">"
                + "".join(f'<option value="{g}">{g}</option>' for g in GROUPS.keys())
                + "</select>"
            )
        else:
            group_cell = f"<span>{user_group}</span>"

        html += rf"""
<tr data-table="{table}">
    <td>{table}</td>

    <td>{group_cell}</td>

    <td>
        <select class="userSelect" onchange="changeUser(this, '{table}')">
            {''.join(f'<option value="{u}">{u}</option>' for u in GROUPS[user_group])}
        </select>
    </td>

    <td>
        <textarea class="notesEditable" placeholder="Enter notes..."></textarea>
    </td>

    <td class="notesReadonly"></td>

    <td>
        <textarea class="messagesBox" placeholder="Leave a message for other users..."></textarea>
    </td>
</tr>
"""

    html += """
</table>

</body>
</html>
"""

    # ---------------------------------------------------------
    # WRITE FILE
    # ---------------------------------------------------------

    os.makedirs(os.path.dirname(HTML_OUTPUT), exist_ok=True)

    with open(HTML_OUTPUT, "w", encoding="utf-8") as f:
        f.write(html)

    print(f"HTML file created: {HTML_OUTPUT}")
    print(f"Tables available to {logged_in_user} ({user_group}): {len(allowed_tables)}")


if __name__ == "__main__":
    generate_table_list_html()
