"""Demo: look up historic EPC records for an address + postcode.

Reads the gzipped CSV at
    s3://retrofit-data-dev/historical_epc/<POSTCODE>/data.csv.gz
scores rows against the user-provided address, and prints the top matches.

Usage:
    python -m scripts.historic_epc_demo "47 Gordon Road" "AB33 8AL"
    python -m scripts.historic_epc_demo  # uses defaults below
"""

import sys

from datatypes.epc.domain.historic_epc_matching import match_addresses_for_postcode
from typing import Optional


def main(user_address: str, postcode: str) -> None:
    print(f"Looking up: {user_address!r} @ {postcode!r}\n")

    result = match_addresses_for_postcode(user_address, postcode)

    print(f"Found {len(result.matches)} candidate row(s).\n")

    print("Top 3 matches:")
    for m in result.top_n(3):
        print(
            f"  rank={m.lexirank}  score={m.lexiscore:.3f}  "
            f"uprn={m.record.uprn or '(none)':<14}  {m.record.address}"
        )

    print()
    uprn: Optional[str] = result.unambiguous_uprn()
    if uprn:
        print(f"Unambiguous UPRN: {uprn}")
    else:
        print("No unambiguous UPRN (zero-score, tie, or empty result).")


if __name__ == "__main__":
    args = sys.argv[1:]
    if len(args) == 2:
        main(args[0], args[1])
    elif len(args) == 0:
        main("47 Gordon Road", "AB33 8AL")
    else:
        print(__doc__)
        sys.exit(2)
