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
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#!/usr/bin/env python3
"""Validate the bilingual fictional technology-ethics microdataset.

SPDX-License-Identifier: MIT
"""

from __future__ import annotations

import argparse
import json
import re
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable


ROOT = Path(__file__).resolve().parent
DEFAULT_DATA = ROOT / "data" / "train.jsonl"

EXPECTED_PAIR_DOMAINS = {
    "ice-tech-ethics-01": "emergency-energy-allocation",
    "ice-tech-ethics-02": "public-safety-surveillance",
    "ice-tech-ethics-03": "algorithmic-resource-governance",
    "ice-tech-ethics-04": "sustainable-computing",
    "ice-tech-ethics-05": "autonomous-access-control",
    "ice-tech-ethics-06": "emotion-recognition",
    "ice-tech-ethics-07": "healthcare-ai",
    "ice-tech-ethics-08": "autonomous-logistics",
    "ice-tech-ethics-09": "generative-ai-memorials",
    "ice-tech-ethics-10": "workplace-algorithms",
    "ice-tech-ethics-11": "biometric-access",
    "ice-tech-ethics-12": "conversational-ai-spiritual-care",
}
EXPECTED_PAIR_MOTIFS = {
    "ice-tech-ethics-01": "geothermal-valley",
    "ice-tech-ethics-02": "glacier-lagoon",
    "ice-tech-ethics-03": "basalt-bay",
    "ice-tech-ethics-04": "winter-greenhouse",
    "ice-tech-ethics-05": "mossy-lava-field",
    "ice-tech-ethics-06": "black-sand-coast",
    "ice-tech-ethics-07": "stormy-fjord",
    "ice-tech-ethics-08": "snowy-highlands",
    "ice-tech-ethics-09": "volcanic-island",
    "ice-tech-ethics-10": "winter-harbor",
    "ice-tech-ethics-11": "lava-ridge-shelter",
    "ice-tech-ethics-12": "glacier-edge-shelter",
}
ALLOWED_CONCEPTS = {
    "care-for-vulnerable",
    "common-good",
    "creation-care",
    "hospitality",
    "human-dignity",
    "humility",
    "justice",
    "love-of-neighbor",
    "non-coercion",
    "remembrance",
    "sabbath-rest",
    "stewardship",
    "truthfulness",
}
PLURALISM_COMMITMENTS = {
    "multiple-worldviews-welcome",
    "no-group-consensus-claim",
    "no-required-assent",
}
REVIEW_FOCUS = {
    "bilingual-equivalence",
    "cultural-non-attribution",
    "technology-ethics",
    "theological-pluralism",
}
RECORD_KEYS = {
    "audience",
    "christian_ethics_concepts",
    "creation",
    "discussion_question",
    "fictionality",
    "id",
    "intended_use",
    "landscape_motif",
    "language",
    "license",
    "pair_id",
    "perspectives",
    "pluralism",
    "scenario_title",
    "setting",
    "status",
    "technology_domain",
    "topic_tags",
    "translation_of",
    "version",
}
ID_PATTERN = re.compile(r"^ice-tech-ethics-(?:0[1-9]|1[0-2])-(?:pt-br|en)$")
PAIR_PATTERN = re.compile(r"^ice-tech-ethics-(?:0[1-9]|1[0-2])$")
SLUG_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
PROHIBITED_PHRASES = {
    "a visão cristã é",
    "aceitar jesus",
    "all christians",
    "christians believe",
    "christians must",
    "converter-se ao cristianismo",
    "cristãos acreditam",
    "cristãos devem",
    "deve acreditar",
    "icelanders believe",
    "islandeses acreditam",
    "must believe",
    "only correct answer",
    "the christian view is",
    "todos os cristãos",
    "única resposta correta",
}


def _read_jsonl(path: Path) -> tuple[list[dict[str, Any]], list[str]]:
    records: list[dict[str, Any]] = []
    errors: list[str] = []
    try:
        lines = path.read_text(encoding="utf-8").splitlines()
    except (OSError, UnicodeError) as exc:
        return [], [f"cannot read {path}: {exc}"]
    for line_number, raw_line in enumerate(lines, 1):
        if not raw_line.strip():
            errors.append(f"line {line_number}: blank JSONL line")
            continue
        try:
            value = json.loads(raw_line, parse_constant=_reject_constant)
        except (json.JSONDecodeError, ValueError) as exc:
            errors.append(f"line {line_number}: invalid JSON: {exc}")
            continue
        if not isinstance(value, dict):
            errors.append(f"line {line_number}: record must be a JSON object")
            continue
        records.append(value)
    return records, errors


def _reject_constant(token: str) -> Any:
    raise ValueError(f"non-standard JSON constant {token!r}")


def _nonempty_text(value: Any, *, minimum: int = 1) -> bool:
    return isinstance(value, str) and len(value.strip()) >= minimum


def _exact_keys(value: Any, expected: set[str]) -> bool:
    return isinstance(value, dict) and set(value) == expected


def _record_text(record: dict[str, Any]) -> str:
    return json.dumps(record, ensure_ascii=False, sort_keys=True).casefold()


def _duplicate_values(values: Iterable[str]) -> set[str]:
    return {value for value, count in Counter(values).items() if count > 1}


def validate_records(records: list[dict[str, Any]]) -> list[str]:
    """Return human-readable validation errors for already parsed records."""

    errors: list[str] = []
    if len(records) != 24:
        errors.append(f"dataset must contain exactly 24 records; found {len(records)}")

    record_ids = [record.get("id") for record in records if isinstance(record.get("id"), str)]
    for duplicate in sorted(_duplicate_values(record_ids)):
        errors.append(f"duplicate record id {duplicate!r}")

    pairs: dict[str, list[dict[str, Any]]] = defaultdict(list)
    for index, record in enumerate(records, 1):
        label = str(record.get("id") or f"line-{index}")
        if set(record) != RECORD_KEYS:
            missing = sorted(RECORD_KEYS - set(record))
            unexpected = sorted(set(record) - RECORD_KEYS)
            errors.append(
                f"{label}: record keys mismatch; missing={missing}, unexpected={unexpected}"
            )

        record_id = record.get("id")
        pair_id = record.get("pair_id")
        language = record.get("language")
        if not isinstance(record_id, str) or not ID_PATTERN.fullmatch(record_id):
            errors.append(f"{label}: invalid id")
        if not isinstance(pair_id, str) or not PAIR_PATTERN.fullmatch(pair_id):
            errors.append(f"{label}: invalid pair_id")
        else:
            pairs[pair_id].append(record)
        if language not in {"pt-BR", "en"}:
            errors.append(f"{label}: language must be pt-BR or en")
        elif isinstance(pair_id, str):
            expected_id = f"{pair_id}-{'pt-br' if language == 'pt-BR' else 'en'}"
            if record_id != expected_id:
                errors.append(f"{label}: id must be {expected_id!r}")

        if record.get("version") != "1.0.0":
            errors.append(f"{label}: version must be '1.0.0'")
        if record.get("status") != "ai-generated-draft-human-review-required":
            errors.append(f"{label}: invalid review status")
        if record.get("license") != "CC-BY-4.0":
            errors.append(f"{label}: license must be CC-BY-4.0")
        if record.get("intended_use") != "facilitated-ethical-discussion":
            errors.append(f"{label}: invalid intended_use")
        if record.get("audience") != ["adult-learners", "educators"]:
            errors.append(f"{label}: audience must be adult-learners and educators")

        expected_domain = EXPECTED_PAIR_DOMAINS.get(pair_id)
        if record.get("technology_domain") != expected_domain:
            errors.append(f"{label}: unexpected technology_domain")
        expected_motif = EXPECTED_PAIR_MOTIFS.get(pair_id)
        if record.get("landscape_motif") != expected_motif:
            errors.append(f"{label}: unexpected landscape_motif")

        if not _nonempty_text(record.get("scenario_title"), minimum=8):
            errors.append(f"{label}: scenario_title is too short")
        if not _nonempty_text(record.get("setting"), minimum=100):
            errors.append(f"{label}: setting must be substantive")
        question = record.get("discussion_question")
        if not _nonempty_text(question, minimum=40) or not question.strip().endswith("?"):
            errors.append(f"{label}: discussion_question must be a substantive question")

        tags = record.get("topic_tags")
        if (
            not isinstance(tags, list)
            or not 2 <= len(tags) <= 5
            or len(tags) != len(set(tags))
            or not all(isinstance(tag, str) and SLUG_PATTERN.fullmatch(tag) for tag in tags)
        ):
            errors.append(f"{label}: topic_tags must contain 2-5 unique slugs")

        concepts = record.get("christian_ethics_concepts")
        if (
            not isinstance(concepts, list)
            or not 2 <= len(concepts) <= 4
            or len(concepts) != len(set(concepts))
            or not set(concepts) <= ALLOWED_CONCEPTS
        ):
            errors.append(f"{label}: invalid christian_ethics_concepts")

        fictionality = record.get("fictionality")
        if not _exact_keys(
            fictionality,
            {"claims_real_icelandic_or_christian_practices", "is_fictional", "notice"},
        ):
            errors.append(f"{label}: invalid fictionality object")
        else:
            if fictionality["is_fictional"] is not True:
                errors.append(f"{label}: scenario must be marked fictional")
            if fictionality["claims_real_icelandic_or_christian_practices"] is not False:
                errors.append(f"{label}: record must disclaim real-practice claims")
            notice = fictionality["notice"]
            expected_terms = ("ficcional", "não descreve") if language == "pt-BR" else ("fictional", "does not describe")
            if not _nonempty_text(notice, minimum=80) or not all(term in notice.casefold() for term in expected_terms):
                errors.append(f"{label}: fictionality notice is incomplete for {language}")

        pluralism = record.get("pluralism")
        if not _exact_keys(pluralism, {"commitments", "required", "safeguard"}):
            errors.append(f"{label}: invalid pluralism object")
        else:
            if pluralism["required"] is not True:
                errors.append(f"{label}: pluralism safeguard must be required")
            commitments = pluralism["commitments"]
            if not isinstance(commitments, list) or set(commitments) != PLURALISM_COMMITMENTS or len(commitments) != 3:
                errors.append(f"{label}: pluralism commitments are incomplete")
            if not _nonempty_text(pluralism["safeguard"], minimum=120):
                errors.append(f"{label}: pluralism safeguard must be substantive")

        creation = record.get("creation")
        if not _exact_keys(creation, {"human_review_status", "method", "review_focus"}):
            errors.append(f"{label}: invalid creation object")
        else:
            if creation["method"] != "ai-generated-original-draft":
                errors.append(f"{label}: creation method must disclose AI generation")
            if creation["human_review_status"] != "required-before-curated-release-or-use":
                errors.append(f"{label}: human review requirement is missing")
            focus = creation["review_focus"]
            if not isinstance(focus, list) or set(focus) != REVIEW_FOCUS or len(focus) != 4:
                errors.append(f"{label}: review_focus is incomplete")

        perspectives = record.get("perspectives")
        if not isinstance(perspectives, list) or len(perspectives) != 2:
            errors.append(f"{label}: exactly two perspectives are required")
        else:
            perspective_ids: list[str] = []
            arguments: list[str] = []
            for perspective_index, perspective in enumerate(perspectives):
                pointer = f"{label}: perspective[{perspective_index}]"
                if not _exact_keys(perspective, {"argument", "id", "questions", "title"}):
                    errors.append(f"{pointer}: invalid object")
                    continue
                perspective_ids.append(perspective["id"])
                arguments.append(perspective["argument"])
                if not _nonempty_text(perspective["title"], minimum=8):
                    errors.append(f"{pointer}: title is too short")
                if not _nonempty_text(perspective["argument"], minimum=120):
                    errors.append(f"{pointer}: argument must be substantive")
                questions = perspective["questions"]
                if (
                    not isinstance(questions, list)
                    or len(questions) != 2
                    or len(set(questions)) != 2
                    or not all(_nonempty_text(item, minimum=20) and item.strip().endswith("?") for item in questions)
                ):
                    errors.append(f"{pointer}: exactly two substantive questions are required")
            if set(perspective_ids) != {"a", "b"} or len(perspective_ids) != 2:
                errors.append(f"{label}: perspective ids must be a and b")
            if len(arguments) == 2 and arguments[0].strip() == arguments[1].strip():
                errors.append(f"{label}: perspectives must present distinct arguments")

        text = _record_text(record)
        for phrase in sorted(PROHIBITED_PHRASES):
            if phrase in text:
                errors.append(f"{label}: prohibited universalizing or proselytizing phrase {phrase!r}")

    expected_pairs = set(EXPECTED_PAIR_DOMAINS)
    if set(pairs) != expected_pairs:
        errors.append(
            f"pair set mismatch; missing={sorted(expected_pairs - set(pairs))}, "
            f"unexpected={sorted(set(pairs) - expected_pairs)}"
        )

    stable_fields = (
        "audience",
        "christian_ethics_concepts",
        "creation",
        "intended_use",
        "landscape_motif",
        "license",
        "status",
        "technology_domain",
        "topic_tags",
        "version",
    )
    for pair_id in sorted(expected_pairs):
        pair_records = pairs.get(pair_id, [])
        languages = [record.get("language") for record in pair_records]
        if len(pair_records) != 2 or Counter(languages) != Counter({"pt-BR": 1, "en": 1}):
            errors.append(f"{pair_id}: pair must contain exactly one pt-BR and one en record")
            continue
        by_language = {record["language"]: record for record in pair_records}
        source = by_language["pt-BR"]
        translated = by_language["en"]
        if source.get("translation_of") is not None:
            errors.append(f"{source['id']}: pt-BR root must have null translation_of")
        if translated.get("translation_of") != source.get("id"):
            errors.append(f"{translated['id']}: en record must translate directly from pt-BR root")
        for field in stable_fields:
            if source.get(field) != translated.get(field):
                errors.append(f"{pair_id}: bilingual invariant {field!r} differs")
        if [item.get("id") for item in source.get("perspectives", [])] != [
            item.get("id") for item in translated.get("perspectives", [])
        ]:
            errors.append(f"{pair_id}: perspective order differs across languages")

    return errors


def validate_repository(data_path: Path = DEFAULT_DATA) -> list[str]:
    """Validate data plus the minimum Hugging Face release files."""

    records, errors = _read_jsonl(data_path)
    errors.extend(validate_records(records))

    readme = ROOT / "README.md"
    license_file = ROOT / "LICENSE"
    try:
        readme_text = readme.read_text(encoding="utf-8")
    except (OSError, UnicodeError) as exc:
        errors.append(f"cannot read {readme}: {exc}")
    else:
        required_card_fragments = (
            "---\nlanguage:\n- pt\n- en\n",
            "license: cc-by-4.0",
            "path: data/train.jsonl",
            "AI-generated",
            "human review",
        )
        for fragment in required_card_fragments:
            if fragment not in readme_text:
                errors.append(f"README.md is missing required fragment {fragment!r}")

    try:
        license_text = license_file.read_text(encoding="utf-8")
    except (OSError, UnicodeError) as exc:
        errors.append(f"cannot read {license_file}: {exc}")
    else:
        if "Creative Commons Attribution 4.0 International" not in license_text:
            errors.append("LICENSE does not identify CC BY 4.0")
        if "https://creativecommons.org/licenses/by/4.0/legalcode" not in license_text:
            errors.append("LICENSE does not link to the official legal code")

    return errors


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data", type=Path, default=DEFAULT_DATA)
    args = parser.parse_args()
    errors = validate_repository(args.data)
    if errors:
        for error in errors:
            print(f"ERROR: {error}")
        return 1
    print("valid: 24 records in 12 pt-BR/en pairs")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())