#!/usr/bin/env python3
"""Regenerate the fictional examples using only the Python standard library."""

import argparse
import csv
import json
import re
from datetime import date
from html import escape
from pathlib import Path
from string import Template

ROOT = Path(__file__).resolve().parent
RESPONDENTS = ROOT / "survey-responses"
WORD_COLUMNS = (
    ("word", "Word"),
    ("part_of_speech", "Part of speech"),
    ("gender_or_aspect", "Gender or aspect"),
    ("meaning", "Meaning"),
    ("example", "Example"),
    ("translation", "Translation"),
    ("note", "Note"),
)
RATINGS = ("q1", "q2", "q3", "q4", "q5")
FREE_TEXT = ("q6_biggest_benefit", "q7_main_concern")
METRICS = (
    ("temperature_c", "Temperature", "°C", "Temp °C", "temperature"),
    ("rainfall_mm", "Rainfall", "mm", "Rain mm", "rainfall"),
    ("wind_kmh", "Wind speed", "km/h", "km/h", "wind"),
)


def read_csv(name):
    with (ROOT / name).open(encoding="utf-8", newline="") as source:
        return list(csv.DictReader(source, strict=True))


def write(path, text):
    path.write_text(text, encoding="utf-8", newline="\n")


def survey_records(rows, codebook):
    entries = {(row["field"], row["code"]): row for row in codebook}
    records = []
    for row in rows:
        record = {"respondent_id": row["respondent_id"]}
        for field in ("role", "discipline"):
            code = row[field]
            entry = entries[field, code]
            record[field] = {
                "question": entry["question"], "code": int(code), "label": entry["label"],
            }
        for field in RATINGS:
            code = row[field]
            record[field] = {
                "question": entries[field, ""]["question"],
                "answer": int(code),
                "label": entries["likert", code]["label"],
            }
        for field in FREE_TEXT:
            entry = entries[field, ""]
            record[field] = {
                "question": entry["question"], "heading": entry["label"], "response": row[field],
            }
        records.append(record)
    return records


def write_respondent(path, record, *, force):
    metadata = {
        "respondent_id": record["respondent_id"],
        "role": record["role"]["label"],
        "discipline": record["discipline"]["label"],
    }
    metadata.update({field: record[field] for field in RATINGS})
    metadata.update({field: record[field]["question"] for field in FREE_TEXT})

    # One JSON-compatible value per line is valid YAML 1.2 frontmatter.
    frontmatter = "\n".join(
        f"{field}: {json.dumps(value, ensure_ascii=False)}"
        for field, value in metadata.items()
    )
    sections = "\n\n".join(
        f"## {record[field]['heading']}\n\n{record[field]['response']}"
        for field in FREE_TEXT
    )
    with path.open("w" if force else "x", encoding="utf-8", newline="\n") as output:
        output.write(f"---\n{frontmatter}\n---\n\n{sections}\n")


def import_survey(*, force):
    if not force and any(RESPONDENTS.glob("respondent-*.md")):
        raise FileExistsError("survey-responses/ already contains respondent files")

    records = survey_records(read_csv("survey-responses.csv"), read_csv("survey-codebook.csv"))
    paths = [RESPONDENTS / f"respondent-{int(record['respondent_id']):03d}.md" for record in records]
    if len(paths) != len(set(paths)):
        raise SystemExit("The survey export contains duplicate respondent IDs.")

    RESPONDENTS.mkdir(exist_ok=True)
    for path, record in zip(paths, records):
        write_respondent(path, record, force=force)


def render_respondent(path):
    # The respondent files use JSON-compatible YAML values, one per line.
    text = path.read_text(encoding="utf-8")
    frontmatter, body = text.removeprefix("---\n").split("\n---\n", 1)
    respondent = {}
    for line in frontmatter.splitlines():
        field, value = line.split(": ", 1)
        respondent[field] = json.loads(value)

    # Each level-two heading labels the free response that follows it.
    _, first_heading, benefit, second_heading, concern = re.split(
        r"^## (.+)\n", body, maxsplit=2, flags=re.MULTILINE
    )

    ratings = []
    for field in RATINGS:
        rating = respondent[field]
        question = escape(rating["question"])
        answer = int(rating["answer"])
        label = escape(rating["label"])
        ratings.append(f"""<li>
  <p>{question}</p>
  <div class="rating"><span class="track" aria-hidden="true"><span style="width:{answer * 20}%"></span></span>
  <span>{answer}/5 · {label}</span></div>
</li>""")
    responses = "".join(
        f'<section><h3>{escape(heading)}</h3><p class="response">{escape(response.strip())}</p></section>'
        for heading, response in ((first_heading, benefit), (second_heading, concern))
    )
    role, discipline = escape(respondent["role"]), escape(respondent["discipline"])
    respondent_id = escape(respondent["respondent_id"])
    return f"""<article class="card respondent" data-role="{role}" data-discipline="{discipline}">
  <header><h2>Respondent {respondent_id}</h2><p>{role} · {discipline}</p></header>
  <div class="record-layout">
    <section><h3>Agreement ratings</h3><ul class="ratings">{''.join(ratings)}</ul></section>
    <div class="free-text">{responses}</div>
  </div>
</article>""", respondent


def filter_group(field, values):
    buttons = [f'<button type="button" data-value="" aria-pressed="true">All {field}s</button>']
    for value in sorted(values):
        label = escape(value)
        buttons.append(f'<button type="button" data-value="{label}" aria-pressed="false">{label}</button>')
    return f'<fieldset data-filter="{field}"><legend>{field.capitalize()}</legend>{"".join(buttons)}</fieldset>'


def build_survey_viewer(paths):
    cards, respondents = zip(*(render_respondent(path) for path in paths))
    filters = "\n".join(filter_group(field, {item[field] for item in respondents})
                        for field in ("role", "discipline"))
    return SURVEY_PAGE.substitute(styles=STYLES, filters=filters, cards="\n".join(cards),
                                  count=len(cards))


def station_plot(metric, readings, dates, ticks):
    field, label, unit, _, colour = metric
    low, _, high = ticks
    first, last = dates[0], dates[-1]
    days = max(1, (last - first).days)

    points = []
    for reading in readings:
        x = 31 + (date.fromisoformat(reading["date"]) - first).days / days * 242
        y = 86 - (float(reading[field]) - low) / (high - low) * 75
        points.append((x, y))
    line = " ".join(f"{x:.2f},{y:.2f}" for x, y in points)
    dots = "".join(f'<circle cx="{x:.2f}" cy="{y:.2f}" r="2.15"/>' for x, y in points)
    grid = "\n".join(
        f'<line x1="31" y1="{y}" x2="273" y2="{y}"/>'
        f'<text x="24" y="{y + 4}" text-anchor="end">{tick:g}</text>'
        for tick, y in zip(ticks, (86, 48.5, 11))
    )
    date_labels = "\n".join(
        f'<text x="{x}" y="104" text-anchor="{anchor}">{day:%d/%m}</text>'
        for x, anchor, day in ((31, "start", first), (273, "end", last))
    )
    station = escape(readings[0]["station"])
    return f"""<section class="plot {colour}">
  <h3>{label} <span>({unit})</span></h3>
  <svg viewBox="0 0 285 110" role="img" aria-label="{label} at {station}, {first} to {last}. Values in the readings table.">
    {grid}
    <polyline points="{line}" fill="none"/>
    <g class="dots">{dots}</g>
    {date_labels}
  </svg>
</section>"""


def build_station_chart(rows):
    dates = sorted({date.fromisoformat(row["date"]) for row in rows})
    grouped = {}
    for row in sorted(rows, key=lambda row: (row["station"], row["date"])):
        grouped.setdefault(row["station"], []).append(row)

    # Each measure has a common scale, so the station panels can be compared.
    scales = {}
    for metric, step in zip(METRICS, (5, 5, 20)):
        field = metric[0]
        values = [float(row[field]) for row in rows]
        base = min(0, int(min(values) // step) * step)
        top = max(step, (int((max(values) - base) // step) + 1) * step) + base
        scales[field] = (base, (base + top) / 2, top)

    charts = []
    for station, readings in grouped.items():
        plots = "".join(station_plot(metric, readings, dates, scales[metric[0]])
                        for metric in METRICS)
        charts.append(f'<article class="card station"><h2>{escape(station)}</h2>{plots}</article>')

    table_rows = []
    for row in rows:
        cells = "".join(f"<td>{escape(row[field])}</td>" for field, *_ in METRICS)
        table_rows.append(
            f'<tr><td><time datetime="{escape(row["date"])}">{escape(row["date"])}</time></td>'
            f'<td>{escape(row["station"])}</td>{cells}</tr>'
        )
    table_headers = "".join(
        f'<th scope="col" aria-label="{label}, {unit}">{short}</th>'
        for _, label, unit, short, _ in METRICS
    )
    return STATION_PAGE.substitute(styles=STYLES, charts="\n".join(charts),
                                   headers=table_headers, rows="\n".join(table_rows),
                                   reading_count=len(rows), station_count=len(grouped),
                                   first=dates[0], last=dates[-1])


def write_word_table(words):
    fields, labels = zip(*WORD_COLUMNS)
    rows = []
    cards = []
    table_rows = []
    for item in words:
        category = "gender" if "gender" in item else "aspect"
        example = item["example"]
        row = (
            item["word"], item["part_of_speech"], item[category], item["meaning"],
            example["sentence"], example["translation"], example["note"],
        )
        rows.append(row)

        values = [escape(value) for value in row]
        for index in (0, 4):
            values[index] = f'<span lang="cs">{values[index]}</span>'
        card_labels = (*labels[:2], category.capitalize(), *labels[3:])
        pairs = [
            f"<div><dt>{label}</dt><dd>{value}</dd></div>"
            for label, value in zip(card_labels, values)
        ]
        cards.append(f'<article class="card word"><dl>{"".join(pairs)}</dl></article>')

        cells = "".join(f"<td>{value}</td>" for value in values[1:])
        table_rows.append(f'<tr><th scope="row">{values[0]}</th>{cells}</tr>')

    with (ROOT / "word-table.csv").open("w", encoding="utf-8", newline="") as output:
        writer = csv.writer(output, lineterminator="\n")
        writer.writerow(fields)
        writer.writerows(rows)

    headers = "".join(f'<th scope="col">{label}</th>' for label in labels)
    write(ROOT / "word-table.html", WORD_PAGE.substitute(
        styles=STYLES + WORD_STYLES, cards="\n".join(cards),
        headers=headers, rows="\n".join(table_rows),
    ))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command")
    importer = commands.add_parser("import-survey", help="import the survey export into Markdown")
    importer.add_argument("--force", action="store_true", help="replace existing records from the export")
    args = parser.parse_args()

    if args.command == "import-survey":
        try:
            import_survey(force=args.force)
        except FileExistsError as error:
            importer.exit(1, f"Refusing to overwrite respondent records ({error}). "
                             "Use --force to replace them from the original export.\n")
        return

    paths = sorted(RESPONDENTS.glob("respondent-*.md"))
    if not paths:
        parser.exit(1, "No respondent records found. Run import-survey to create them.\n")
    write(ROOT / "survey-viewer.html", build_survey_viewer(paths))
    write(ROOT / "station-readings-chart.html", build_station_chart(read_csv("station-readings.csv")))
    write_word_table(json.loads((ROOT / "word-table.json").read_text(encoding="utf-8")))


STYLES = """
:root {
  color-scheme: light dark;
  --bg: #f6f5ef;
  --surface: #fffcf6;
  --text: #242c2a;
  --muted: #4d5a54;
  --rule: #bec8bf;
  --accent: #076c59;
  --on-accent: #fff;
  --soft: #e0ebe3;
  --rain: #235c92;
  --wind: #924514;
}
@media (prefers-color-scheme: dark) {
  :root {
    --bg: #161e1c;
    --surface: #202b27;
    --text: #edf3ec;
    --muted: #becdc2;
    --rule: #52665a;
    --accent: #7bd8bb;
    --on-accent: #152620;
    --soft: #31463c;
    --rain: #9cc9f8;
    --wind: #f2ae72;
  }
}
* { box-sizing: border-box; }
body {
  margin: 0;
  background: var(--bg);
  color: var(--text);
  font: 1rem/1.55 system-ui, sans-serif;
}
main { width: min(100% - 2rem, 70rem); margin-inline: auto; padding-block: 2.5rem 4rem; }
h1, h2, h3, p { margin: 0; }
h1 { font-size: clamp(1.95rem, 5vw, 3rem); line-height: 1.08; letter-spacing: -.035em; }
h2 { font-size: 1.3rem; line-height: 1.25; }
h3 { font-size: .96rem; }
.intro { border-block-start: 4px solid var(--accent); padding-block: 1.2rem 1.5rem; }
.intro p, .respondent header p, .station h3 span, .result-count { color: var(--muted); }
.intro p { margin-top: .55rem; }
.card, .filters, .readings {
  border: 1px solid var(--rule);
  border-radius: .65rem;
  background: var(--surface);
}
.stations { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1rem; }
.station { padding: 1rem; }
.station h2 { margin-bottom: .75rem; }
.plot + .plot { border-top: 1px solid var(--rule); padding-top: .6rem; margin-top: .15rem; }
.plot svg { display: block; width: 100%; max-width: 26rem; margin-inline: auto; }
.plot text { fill: var(--muted); font: 11px system-ui, sans-serif; }
.plot line { stroke: var(--rule); }
.plot polyline { stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; stroke: var(--series); }
.plot .dots { fill: var(--series); }
.temperature { --series: var(--accent); }
.rainfall { --series: var(--rain); }
.wind { --series: var(--wind); }
.readings { margin-top: 1.35rem; padding: clamp(.55rem, 2.5vw, 1rem); }
table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
caption {
  text-align: left;
  font-size: 1.3rem;
  font-weight: 700;
  padding: .2rem .25rem .65rem;
}
th, td { text-align: right; padding: .47rem .35rem; border-top: 1px solid var(--rule); }
th:nth-child(-n+2), td:nth-child(-n+2) { text-align: left; }
thead { background: var(--soft); }
.filters { padding: 1rem; }
.filters label { display: block; font-weight: 700; }
input, button { font: inherit; color: inherit; }
input {
  width: min(100%, 29rem);
  display: block;
  margin-top: .3rem;
  padding: .55rem .7rem;
  border: 1px solid var(--rule);
  border-radius: .35rem;
  background: var(--bg);
}
fieldset { min-width: 0; border: 0; padding: 0; margin: .8rem 0 0; }
legend { padding: 0; font-weight: 700; }
button {
  cursor: pointer;
  min-height: 2.75rem;
  margin: .3rem .3rem 0 0;
  padding: .3rem .62rem;
  border: 1px solid var(--rule);
  border-radius: .35rem;
  background: var(--surface);
}
button[aria-pressed="true"] { background: var(--accent); color: var(--on-accent); border-color: var(--accent); }
button:hover:not([aria-pressed="true"]) { background: var(--soft); }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.result-count { margin: .8rem 0 .5rem; }
.respondent { padding: clamp(.9rem, 3vw, 1.4rem); margin-bottom: .8rem; }
.respondent header { border-bottom: 1px solid var(--rule); padding-bottom: .8rem; }
.record-layout { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); gap: 1.5rem; margin-top: .9rem; }
.ratings { list-style: none; margin: .45rem 0 0; padding: 0; }
.ratings li + li { margin-top: .7rem; }
.ratings p { font-size: .925rem; }
.rating { display: flex; gap: .55rem; align-items: center; margin-top: .12rem; color: var(--muted); font-size: .82rem; }
.track { flex: 0 0 3.7rem; height: .36rem; border-radius: 1rem; background: var(--soft); }
.track span { display: block; height: 100%; border-radius: inherit; background: var(--accent); }
.free-text section + section { margin-top: 1rem; }
.response { margin-top: .32rem; white-space: pre-wrap; overflow-wrap: anywhere; }
@media (max-width: 44rem) {
  main { padding-top: 1.25rem; }
  .stations, .record-layout { grid-template-columns: minmax(0, 1fr); }
  .record-layout { gap: 1.1rem; }
  table { font-size: .82rem; }
}
"""

WORD_STYLES = """
.word-cards { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; }
.word { padding: 1rem; }
.word dl, .word dd { margin: 0; }
.word dl > div {
  display: grid;
  grid-template-columns: minmax(0, 7.5rem) minmax(0, 1fr);
  gap: .45rem;
  padding-block: .3rem;
  overflow-wrap: anywhere;
}
.word dt { color: var(--muted); font-weight: 650; }
.word dl > div:first-child {
  align-items: baseline;
  border-bottom: 1px solid var(--rule);
  margin-bottom: .4rem;
}
.word dl > div:first-child dd { font-size: 1.3rem; font-weight: 700; }
.word-table { overflow-x: auto; }
.word-table:focus-visible { outline-offset: -3px; }
.word-table table { min-width: 42rem; }
.word-table th, .word-table td { text-align: left; vertical-align: top; }
@media (max-width: 44rem) {
  .word-cards { grid-template-columns: minmax(0, 1fr); }
}
"""

WORD_PAGE = Template("""<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Czech words for beginners</title>
<style>$styles</style>
</head>
<body>
<main>
<header class="intro">
  <h1>Czech words for beginners</h1>
  <p>Each card keeps a word, its grammar and an example together.</p>
</header>
<div class="word-cards">
$cards
</div>
<div class="readings word-table" role="region" aria-labelledby="word-table-caption" tabindex="0">
  <table>
    <caption id="word-table-caption">The same words in a table</caption>
    <thead><tr>$headers</tr></thead>
    <tbody>
$rows
    </tbody>
  </table>
</div>
</main>
</body>
</html>
""")

STATION_PAGE = Template("""<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fictional station readings</title>
<style>$styles</style>
</head>
<body>
<main>
<header class="intro">
  <h1>Fictional station readings</h1>
  <p>$reading_count daily readings across $station_count invented stations · $first to $last</p>
</header>
<div class="stations">
$charts
</div>
<div class="readings">
  <table>
    <caption>Daily readings</caption>
    <thead><tr><th scope="col">Date</th><th scope="col">Station</th>$headers</tr></thead>
    <tbody>
$rows
    </tbody>
  </table>
</div>
</main>
</body>
</html>
""")

SURVEY_PAGE = Template("""<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AI in research · Fictional survey</title>
<style>$styles</style>
</head>
<body>
<main>
<header class="intro">
  <h1>AI in research</h1>
  <p>Fictional survey responses from $count invented respondents.</p>
</header>
<div class="filters">
  <label for="search">Search free responses</label>
  <input id="search" type="search">
  $filters
</div>
<p class="result-count" role="status">Showing $count of $count respondents</p>
<div class="respondents">
$cards
</div>
</main>
<script>
const search = document.querySelector('#search');
const groups = [...document.querySelectorAll('[data-filter]')];
const cards = [...document.querySelectorAll('.respondent')];
const status = document.querySelector('.result-count');

function updateResults() {
  const words = search.value.trim().toLowerCase().split(/\\s+/);
  const filters = groups.map(group => [
    group.dataset.filter,
    group.querySelector('[aria-pressed="true"]').dataset.value,
  ]);
  let shown = 0;
  for (const card of cards) {
    const responses = [...card.querySelectorAll('.response')]
      .map(response => response.textContent.toLowerCase()).join(' ');
    card.hidden = !filters.every(([field, value]) => !value || card.dataset[field] === value)
      || !words.every(word => responses.includes(word));
    if (!card.hidden) shown += 1;
  }
  status.textContent = shown
    ? 'Showing ' + shown + ' of ' + cards.length + ' respondents'
    : 'No matching respondents';
}

for (const group of groups) {
  group.addEventListener('click', event => {
    const button = event.target.closest('button');
    if (!button) return;
    group.querySelector('[aria-pressed="true"]').setAttribute('aria-pressed', 'false');
    button.setAttribute('aria-pressed', 'true');
    updateResults();
  });
}
search.addEventListener('input', updateResults);
updateResults();
</script>
</body>
</html>
""")


if __name__ == "__main__":
    main()
