#!/usr/bin/env python3
import csv
import html
from pathlib import Path

base = Path("/mnt/pool/Spatial/MSDatabase")
csv_dir = base / "csv"
html_dir = base / "html"

html_dir.mkdir(parents=True, exist_ok=True)

for csv_file in csv_dir.glob("*.csv"):
    with csv_file.open(newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))

    if not rows:
        continue

    number_string = rows[0].get("Number_string", csv_file.stem)
    columns = list(rows[0].keys())
    th = "".join(f"<th>{html.escape(col)}</th>" for col in columns)

    body_rows = []
    for row in rows:
        tds = "".join(f"<td>{html.escape(str(row.get(col, '')))}</td>" for col in columns)
        body_rows.append(f"<tr>{tds}</tr>")
    tbody = "\n".join(body_rows)

    page = f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>{html.escape(number_string)}</title>
  <style>
    body {{ font-family: Arial, sans-serif; margin: 24px; line-height: 1.4; }}
    h1 {{ margin-bottom: 0.3em; }}
    table {{ border-collapse: collapse; width: 100%; margin-top: 16px; }}
    th, td {{ border: 1px solid #bbb; padding: 8px; text-align: left; vertical-align: top; }}
    th {{ background: #eee; }}
  </style>
</head>
<body>
  <h1>Drive Record: {html.escape(number_string)}</h1>
  <table>
    <thead><tr>{th}</tr></thead>
    <tbody>
{tbody}
    </tbody>
  </table>
</body>
</html>
"""
    out_file = html_dir / f"{csv_file.stem}.html"
    out_file.write_text(page, encoding="utf-8")

print("Rendered HTML files to", html_dir)
