# step6_archive.py — the history signal.
# An archive of past disasters. We search it with today's words.
# A past day that shares many words with today is a warning.
# New here: words(), search() and archive_score().

# Words that every text shares. They say nothing, so the search ignores them.
STOP_WORDS = {"the", "and", "for", "with", "from"}

ARCHIVE = [
    {"year": 2004, "kind": "tsunami", "place": "Khao Lak and Phuket",
     "text": "26 December 2004. The sea pulled back from the beach. Then big waves came. "
             "About 5,400 people died in Thailand. There was no warning system."},
    {"year": 2005, "kind": "flood", "place": "Chiang Mai",
     "text": "A big flood hit Chiang Mai city. River water entered the streets."},
    {"year": 2011, "kind": "flood", "place": "Central Thailand",
     "text": "Heavy monsoon rain from July to January. 815 people died. 65 provinces "
             "flooded. Factories north of Bangkok were under water."},
    {"year": 2011, "kind": "flood", "place": "Chiang Mai",
     "text": "A big flood hit Chiang Mai city again. The Ping River rose over "
             "its banks."},
    {"year": 2014, "kind": "earthquake", "place": "Mae Lao, Chiang Rai",
     "text": "5 May 2014. Magnitude 6.1. One person died. Temples cracked. "
             "The strongest earthquake ever recorded in Thailand."},
    {"year": 2024, "kind": "flood", "place": "Mae Sai, Chiang Rai",
     "text": "September 2024. Rain from Typhoon Yagi. Mae Sai town flooded. "
             "More than 1,000 homes were damaged."},
    {"year": 2024, "kind": "flood", "place": "Chiang Mai",
     "text": "26 September 2024. Heavy rain for days. The Ping River rose over its "
             "banks at 4.93 metres. Markets and roads flooded."},
    {"year": 2024, "kind": "flood", "place": "Chiang Mai",
     "text": "5 and 6 October 2024. The Ping River reached 5.30 metres at Nawarat "
             "Bridge, the highest in 50 years. Night Bazaar was under a metre of water."},
    {"year": 2025, "kind": "earthquake", "place": "Myanmar and Thailand",
     "text": "28 March 2025. Magnitude 7.7 on the Sagaing Fault. Felt in Chiang Mai. "
             "A tower under construction fell in Bangkok."},
]


def ramp(value, low, high):
    """0 below low, 1 above high, a straight line between them."""
    if value <= low:
        return 0.0
    if value >= high:
        return 1.0
    return (value - low) / (high - low)


def words(text):
    """The words in a text: lower case, three letters or more, and not a stop word."""
    cleaned = "".join(letter.lower() if letter.isalnum() else " " for letter in text)
    kept = (word for word in cleaned.split() if len(word) >= 3)
    return {word for word in kept if word not in STOP_WORDS}


def search(query, archive):
    """Every record with the count of words it shares with the query, best first."""
    query_words = words(query)
    matches = []
    for record in archive:
        record_text = record["text"] + " " + record["place"] + " " + record["kind"]
        shared = query_words & words(record_text)
        matches.append((len(shared), record, sorted(shared)))
    matches.sort(key=lambda match: match[0], reverse=True)
    return matches


def archive_score(shared_words):
    """One shared word is chance. Four shared words is a real match."""
    return ramp(shared_words, 1, 4)


def main():
    query = "heavy rain for days, the river is rising, markets near the river"
    print("query:", query)
    for count, record, shared in search(query, ARCHIVE)[:3]:
        print(f"  {count} shared {record['year']} {record['kind']:10} "
              f"{record['place']:22} {shared}")
    best_count = search(query, ARCHIVE)[0][0]
    print(f"archive score: {archive_score(best_count):.2f}")


if __name__ == "__main__":
    main()
