File size: 11,761 Bytes
4189555
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
#!/usr/bin/env python3
"""Create blinded publishable datasets from raw and temporary inputs.

Inputs:
  - temporary/all_email_blasts_consolidated.csv
  - temporary/sampled_email_addresses.csv
  - temporary/sampled_courses.csv
  - raw_data/expirations.csv
  - raw_data/orders.csv
  - .env with LARGE_BLAST_SIZE

Outputs:
    - published_data/email_blasts.parquet
    - published_data/expirations.parquet
    - published_data/orders.parquet

Blinded indexes are the 0-based row positions from the sampled CSV files,
excluding the header row.
"""

from __future__ import annotations

import argparse
import csv
from decimal import Decimal, InvalidOperation
from pathlib import Path

import pyarrow as pa
import pyarrow.parquet as pq


def parse_args() -> argparse.Namespace:
    project_root = Path(__file__).resolve().parent.parent
    parser = argparse.ArgumentParser(
        description="Create publishable blinded datasets from sampled inputs."
    )
    parser.add_argument(
        "--blast-file",
        default=str(project_root / "temporary" / "all_email_blasts_consolidated.csv"),
    )
    parser.add_argument(
        "--sampled-emails-file",
        default=str(project_root / "temporary" / "sampled_email_addresses.csv"),
    )
    parser.add_argument(
        "--sampled-courses-file",
        default=str(project_root / "temporary" / "sampled_courses.csv"),
    )
    parser.add_argument(
        "--expirations-file",
        default=str(project_root / "raw_data" / "expirations.csv"),
    )
    parser.add_argument(
        "--orders-file",
        default=str(project_root / "raw_data" / "orders.csv"),
    )
    parser.add_argument(
        "--env-file",
        default=str(project_root / ".env"),
    )
    parser.add_argument(
        "--output-folder",
        default=str(project_root / "published_data"),
    )
    return parser.parse_args()


def read_env_values(env_path: Path) -> dict[str, str]:
    if not env_path.exists():
        raise FileNotFoundError(f"Required env file not found: {env_path}")

    values: dict[str, str] = {}
    with env_path.open("r", encoding="utf-8") as f:
        for line in f:
            stripped = line.strip()
            if not stripped or stripped.startswith("#") or "=" not in stripped:
                continue
            key, value = stripped.split("=", 1)
            values[key.strip()] = value.strip().strip('"').strip("'")
    return values


def read_required_large_blast_size(env_path: Path) -> int:
    values = read_env_values(env_path)
    raw = values.get("LARGE_BLAST_SIZE", "")
    if not raw:
        raise RuntimeError(f"LARGE_BLAST_SIZE was not found or empty in: {env_path}")
    try:
        return int(raw)
    except ValueError as exc:
        raise RuntimeError(
            f"LARGE_BLAST_SIZE must be an integer in: {env_path}"
        ) from exc


def read_index_map(path: Path, required_header: str) -> dict[str, int]:
    if not path.exists():
        raise FileNotFoundError(f"Required sampled file not found: {path}")

    mapping: dict[str, int] = {}
    with path.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        if not reader.fieldnames:
            raise RuntimeError(f"Sampled file has no header: {path}")
        if required_header not in reader.fieldnames:
            raise RuntimeError(
                f"Sampled file missing required '{required_header}' column: {path}"
            )

        for index, row in enumerate(reader):
            key = (row.get(required_header) or "").strip().lower()
            if not key:
                raise RuntimeError(
                    f"Blank {required_header} value found at sampled index {index} in: {path}"
                )
            if key in mapping:
                raise RuntimeError(
                    f"Duplicate {required_header} value found in sampled file: {key}"
                )
            mapping[key] = index

    if not mapping:
        raise RuntimeError(f"No sampled values found in: {path}")

    return mapping


def read_blast_exp_columns(blast_path: Path) -> list[str]:
    if not blast_path.exists():
        raise FileNotFoundError(f"Required blast file not found: {blast_path}")

    with blast_path.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        if not reader.fieldnames:
            raise RuntimeError(f"Blast file has no header: {blast_path}")
        return [
            col for col in reader.fieldnames if col and col.strip().lower().endswith("_exp")
        ]


def get_blast_course_columns(
    exp_columns: list[str], course_index_map: dict[str, int]
) -> list[tuple[int, str, str]]:
    blinded_columns: list[tuple[int, str, str]] = []
    for exp_col in exp_columns:
        course_name = exp_col.strip().lower().removesuffix("_exp")
        if course_name not in course_index_map:
            raise RuntimeError(
                f"Course from blast column not found in sampled courses: {course_name}"
            )
        course_index = course_index_map[course_name]
        blinded_columns.append(
            (course_index, exp_col, f"blinded_course_{course_index}_exp")
        )
    blinded_columns.sort(key=lambda item: (item[0], item[2]))
    return blinded_columns


def parse_decimal(value: str) -> Decimal:
    try:
        return Decimal(value)
    except InvalidOperation as exc:
        raise RuntimeError(f"Invalid decimal value: {value}") from exc


def write_parquet_rows(rows: list[dict[str, object]], fieldnames: list[str], output_path: Path) -> None:
    columns = {name: [row.get(name) for row in rows] for name in fieldnames}
    table = pa.table(columns)
    pq.write_table(table, output_path)


def create_published_blasts(
    blast_path: Path,
    output_path: Path,
    email_index_map: dict[str, int],
    large_blast_size: int,
    blast_course_columns: list[tuple[int, str, str]],
) -> int:
    blinded_exp_columns = [target_col for _, _, target_col in blast_course_columns]
    fieldnames = [
        "sent_at",
        "is_large_blast",
        "email_blinded_index",
        *blinded_exp_columns,
    ]

    rows: list[dict[str, object]] = []
    with blast_path.open("r", encoding="utf-8", newline="") as src:
        reader = csv.DictReader(src)

        for row in reader:
            email = (row.get("email") or "").strip().lower()
            if email not in email_index_map:
                continue

            sent_at = (row.get("sent_at") or "").strip()
            if not sent_at:
                raise RuntimeError("Blast row missing required sent_at value")

            total_recipients_raw = (row.get("total_recipients_of_batch") or "").strip()
            try:
                total_recipients = int(total_recipients_raw)
            except ValueError as exc:
                raise RuntimeError(
                    f"Invalid total_recipients_of_batch value: {total_recipients_raw}"
                ) from exc

            out_row = {
                "sent_at": sent_at,
                "is_large_blast": 1 if total_recipients >= large_blast_size else 0,
                "email_blinded_index": email_index_map[email],
            }
            for _, source_col, target_col in blast_course_columns:
                out_row[target_col] = (row.get(source_col) or "").strip()
            rows.append(out_row)

    rows.sort(
        key=lambda row: (
            str(row["sent_at"]),
            int(row["is_large_blast"]),
            int(row["email_blinded_index"]),
            *[str(row[col]) for col in blinded_exp_columns],
        )
    )

    write_parquet_rows(rows, fieldnames, output_path)

    return len(rows)


def create_published_expirations(
    expirations_path: Path,
    output_path: Path,
    email_index_map: dict[str, int],
    course_index_map: dict[str, int],
) -> int:
    fieldnames = [
        "email_blinded_index",
        "expired_date",
        "course_blinded_index",
        "our_course",
    ]

    rows: list[dict[str, object]] = []
    with expirations_path.open("r", encoding="utf-8", newline="") as src:
        reader = csv.DictReader(src)

        for row in reader:
            email = (row.get("email") or "").strip().lower()
            if email not in email_index_map:
                continue

            certification = (row.get("certification") or "").strip().lower()
            if certification not in course_index_map:
                raise RuntimeError(
                    f"Certification not found in sampled courses: {certification}"
                )

            rows.append(
                {
                    "email_blinded_index": email_index_map[email],
                    "expired_date": (row.get("expired_date") or "").strip(),
                    "course_blinded_index": course_index_map[certification],
                    "our_course": (row.get("our_course") or "").strip(),
                }
            )

    rows.sort(
        key=lambda row: (
            int(row["email_blinded_index"]),
            str(row["expired_date"]),
            int(row["course_blinded_index"]),
            str(row["our_course"]),
        )
    )

    write_parquet_rows(rows, fieldnames, output_path)

    return len(rows)


def create_published_orders(
    orders_path: Path,
    output_path: Path,
    email_index_map: dict[str, int],
) -> int:
    fieldnames = ["created_at", "email_blinded_index", "price"]
    rows: list[dict[str, object]] = []

    with orders_path.open("r", encoding="utf-8", newline="") as src:
        reader = csv.DictReader(src)

        for row in reader:
            email = (row.get("email") or "").strip().lower()
            if email not in email_index_map:
                continue

            rows.append(
                {
                    "created_at": (row.get("created_at") or "").strip(),
                    "email_blinded_index": email_index_map[email],
                    "price": (row.get("price") or "").strip(),
                }
            )

    rows.sort(
        key=lambda row: (
            str(row["created_at"]),
            int(row["email_blinded_index"]),
            parse_decimal(str(row["price"])),
        )
    )

    write_parquet_rows(rows, fieldnames, output_path)

    return len(rows)


def main() -> None:
    args = parse_args()
    blast_path = Path(args.blast_file)
    sampled_emails_path = Path(args.sampled_emails_file)
    sampled_courses_path = Path(args.sampled_courses_file)
    expirations_path = Path(args.expirations_file)
    orders_path = Path(args.orders_file)
    env_path = Path(args.env_file)
    output_folder = Path(args.output_folder)

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

    large_blast_size = read_required_large_blast_size(env_path)
    email_index_map = read_index_map(sampled_emails_path, "email")
    course_index_map = read_index_map(sampled_courses_path, "course")
    exp_columns = read_blast_exp_columns(blast_path)
    blast_course_columns = get_blast_course_columns(exp_columns, course_index_map)

    blast_rows = create_published_blasts(
        blast_path,
        output_folder / "email_blasts.parquet",
        email_index_map,
        large_blast_size,
        blast_course_columns,
    )
    expiration_rows = create_published_expirations(
        expirations_path,
        output_folder / "expirations.parquet",
        email_index_map,
        course_index_map,
    )
    order_rows = create_published_orders(
        orders_path,
        output_folder / "orders.parquet",
        email_index_map,
    )

    print(f"Published blast rows: {blast_rows:,}")
    print(f"Published expiration rows: {expiration_rows:,}")
    print(f"Published order rows: {order_rows:,}")
    print(f"Output folder: {output_folder}")


if __name__ == "__main__":
    main()