"""Compare Kashiwa City's two October resident-register CSVs (CC BY 4.0)."""

import csv
from datetime import date
from pathlib import Path
import re
import sys


HEADER = ["年月日", "住所コード", "大字町丁", "計", "男", "女", "世帯数"]
NUMBERS = ["計", "男", "女", "世帯数"]


def read_register(path, expected_date):
    with path.open(encoding="utf-8-sig", newline="") as source:
        reader = csv.DictReader(source, strict=True)
        if reader.fieldnames != HEADER:
            raise ValueError(f"{path}: unexpected CSV header")
        records = {}
        for number, row in enumerate(reader, start=2):
            code = row["住所コード"]
            if None in row or not re.fullmatch(r"0|[0-9]{4}", code or ""):
                raise ValueError(f"{path}: invalid record {number}")
            if code in records or not row["大字町丁"]:
                raise ValueError(f"{path}: repeated code or missing name at {number}")
            if date.fromisoformat(row["年月日"].replace("/", "-")) != expected_date:
                raise ValueError(f"{path}: unexpected date at {number}")
            values = []
            for field in NUMBERS:
                value = row[field]
                if not re.fullmatch(r"(?:[0-9]+|[0-9]{1,3}(?:,[0-9]{3})+)", value or ""):
                    raise ValueError(f"{path}: invalid count at {number} ({field})")
                values.append(int(value.replace(",", "")))
            if values[0] != values[1] + values[2]:
                raise ValueError(f"{path}: population breakdown mismatch at {number}")
            records[code] = (row["大字町丁"], values, number)
    total = records.get("0")
    towns = [record for code, record in records.items() if code != "0"]
    if not total or total[0] != "総数" or [
        sum(values[i] for _, values, _ in towns) for i in range(len(NUMBERS))
    ] != total[1]:
        raise ValueError(f"{path}: town totals do not match the city total")
    return records


def compare(previous, current, destination):
    if previous.keys() != current.keys():
        raise ValueError("Address codes differ between the two input years")
    for code, (name, _, _) in current.items():
        if previous[code][0] != name:
            raise ValueError(f"Town name changed for address code {code}")
    with destination.open("w", encoding="utf-8", newline="") as output:
        writer = csv.writer(output, lineterminator="\n")
        writer.writerow([
            "住所コード", "大字町丁", "2025年人口", "2026年人口", "人口増減",
            "2025年世帯数", "2026年世帯数", "世帯数増減", "2025年原表行", "2026年原表行",
        ])
        for code, (name, values, number) in current.items():
            _, old_values, old_number = previous[code]
            writer.writerow([
                code, name, old_values[0], values[0], values[0] - old_values[0],
                old_values[3], values[3], values[3] - old_values[3], old_number, number,
            ])


if __name__ == "__main__":
    if len(sys.argv) != 4:
        raise SystemExit("Usage: python3 compare.py OCT2025.csv OCT2026.csv OUTPUT.csv")
    previous_file, current_file, output_file = map(Path, sys.argv[1:])
    previous = read_register(previous_file, date(2025, 10, 31))
    current = read_register(current_file, date(2026, 10, 31))
    compare(previous, current, output_file)
