#!/usr/bin/env python3
"""
teanglann-check  —  which of the three dialects actually recorded this word?

teanglann.ie (Foras na Gaeilge / New English-Irish Dictionary) hosts real
native-speaker recordings in three dialects:
    CanC = Connacht   (Connemara / Cois Fharraige)
    CanM = Munster
    CanU = Ulster

The recordings live at  https://www.teanglann.ie/<Code>/<word>.mp3  and there
is no index of which words are recorded. Inflected and oblique forms (dhuit,
duit, ...) often simply 404 -- you only find out by asking. This script asks,
for all three dialects at once, and tells you which ones exist.

Written on iLands, 2026-10-03, because that 404 on "dhuit" cost me an hour and
I would rather the next learner not lose it.

Usage:
    python3 teanglann-check.py fáilte
    python3 teanglann-check.py dhuit duit grá
    python3 teanglann-check.py --json máthair

Dedication: do Niocl\u00e1is\u00edn C\u00f3il\u00edn de Ghlost\u00e9ir, a cheartaigh mo
Ghaeilge ar GAELIC-L agus a mh\u00fan an difr\u00edocht idir 'a chairde' agus 'agat'.
Notes:
    - Needs a real browser User-Agent, otherwise the server answers 503.
    - Paced ~1.2 s between requests so a run does not look like a scrape.
    - Requires only the Python standard library.
"""

import argparse
import json
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

UA = (
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/120.0 Safari/537.36"
)
DIALECTS = [
    ("CanC", "Connacht", "Connacht / Cois Fharraige"),
    ("CanM", "Munster", "Munster"),
    ("CanU", "Ulster", "Ulster"),
]
URL_TMPL = "https://www.teanglann.ie/{code}/{word}.mp3"


def probe(code: str, word: str) -> dict:
    """Return {'url': ..., 'exists': True/False, 'status': int|None}."""
    url = URL_TMPL.format(code=code, word=urllib.parse.quote(word, safe=""))
    req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": UA})
    try:
        with urllib.request.urlopen(req, timeout=20) as resp:
            return {"url": url, "exists": True, "status": resp.status}
    except urllib.error.HTTPError as e:
        return {"url": url, "exists": False, "status": e.code}
    except Exception as e:  # network hiccup, timeout, DNS ...
        return {"url": url, "exists": False, "status": None, "error": str(e)}


def check(word: str) -> dict:
    rows = {}
    for i, (code, short, full) in enumerate(DIALECTS):
        rows[code] = {"short": short, "full": full}
        rows[code].update(probe(code, word))
        if i < len(DIALECTS) - 1:
            time.sleep(1.2)
    found = [rows[c]["short"] for c, _, _ in DIALECTS if rows[c]["exists"]]
    return {"word": word, "dialects": rows, "found": found}


def render(result: dict) -> str:
    lines = ["", f"  {result['word']}"]
    for code, short, _full in DIALECTS:
        info = result["dialects"][code]
        mark = "ok " if info["exists"] else " --"
        lines.append(f"    [{mark}] {short:<9} {info['url']}")
    if result["found"]:
        lines.append(f"    recorded in: {', '.join(result['found'])}")
    else:
        lines.append("    no recording found in any dialect.")
    return "\n".join(lines)


def main() -> int:
    ap = argparse.ArgumentParser(
        description="Check which teanglann.ie dialect recordings exist for a word."
    )
    ap.add_argument("words", nargs="+", help="Irish word(s) to check")
    ap.add_argument("--json", action="store_true", help="emit JSON instead of text")
    args = ap.parse_args()

    results = [check(w) for w in args.words]

    if args.json:
        print(json.dumps(results, ensure_ascii=False, indent=2))
    else:
        for r in results:
            print(render(r))

    # exit non-zero if nothing at all was found for any word
    return 0 if any(r["found"] for r in results) else 1


if __name__ == "__main__":
    sys.exit(main())
