"""Join the three Minato CSVs without inferring matches across district names."""

import argparse
import csv
import json
import sys
import unicodedata
from pathlib import Path
from urllib.parse import urlsplit


def normalize(value):
    return unicodedata.normalize("NFKC", value or "").strip()


def index_csv(path, district_field, name_field):
    records = {}
    skipped = 0
    with path.open(encoding="utf-8-sig", newline="") as source:
        for number, row in enumerate(csv.DictReader(source), 2):
            district = normalize(row[district_field]).replace("・", "")
            name = normalize(row[name_field])
            if not district or not name:
                skipped += 1
                continue
            key = (district, name)
            if key in records:
                raise ValueError(f"{path}: duplicate match key on CSV record {number}: {key}")
            records[key] = (number, row)
    return records, skipped


def survey_fields(record):
    if record is None:
        return ["", "", ""]
    number, row = record
    return [str(number), row["緑被率[％]"].strip(), row["調査区域面積[平方メートル]"].strip()]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("directory_csv", type=Path)
    parser.add_argument("survey_2016_csv", type=Path)
    parser.add_argument("survey_2021_csv", type=Path)
    parser.add_argument("output_csv", type=Path)
    args = parser.parse_args()
    parks, park_skipped = index_csv(args.directory_csv, "地区", "ページタイトル")
    previous, previous_skipped = index_csv(args.survey_2016_csv, "総合支所", "名称")
    latest, latest_skipped = index_csv(args.survey_2021_csv, "総合支所", "名称")
    with args.output_csv.open("w", encoding="utf-8", newline="") as output:
        writer = csv.writer(output, lineterminator="\n")
        writer.writerow(["公園名", "地区", "所在地", "区の施設ページ", "施設名簿のレコード",
                         "2016年度のレコード", "2016年度の緑被率", "2016年度の調査区域面積",
                         "2021年度のレコード", "2021年度の緑被率", "2021年度の調査区域面積"])
        for key, (number, row) in parks.items():
            url = row["ファイルパス"]
            authority = urlsplit(url)
            if authority.scheme != "https" or authority.hostname != "www.city.minato.tokyo.jp":
                raise ValueError(f"Unexpected facility link in CSV record {number}")
            writer.writerow([row["ページタイトル"], row["地区"], row["所在地"], url, number,
                             *survey_fields(previous.get(key)), *survey_fields(latest.get(key))])
    meta = {
        "directory": len(parks), "survey_2016": len(previous), "survey_2021": len(latest),
        "matched_2016": len(parks.keys() & previous.keys()),
        "matched_2021": len(parks.keys() & latest.keys()),
        "matched_both": len(parks.keys() & previous.keys() & latest.keys()),
        "skipped_non_data": [park_skipped, previous_skipped, latest_skipped],
    }
    print(json.dumps(meta, ensure_ascii=False), file=sys.stderr)


if __name__ == "__main__":
    main()
