#!/usr/bin/env python3
"""Classify Teton County, WY parcel owners (county GIS ownership layer).

Source: https://maps.terragis.net/tetonwy/mapserver/download/data/ownership.gpkg
Layer: ownership

The GeoPackage is expected at raw/ownership.gpkg next to this script.
The script writes summary.json beside itself and does not write a per-parcel file.
"""
import collections
import json
import re
import sqlite3
from pathlib import Path

ROOT = Path(__file__).resolve().parent
GPKG = ROOT / "raw" / "ownership.gpkg"
SUMMARY = ROOT / "summary.json"


def word_pattern(pats):
    return re.compile(r"(?<![A-Z])(" + "|".join(pats) + r")(?![A-Z])")


NONPROFIT_GOV = word_pattern([
    r"HOMEOWNERS",
    r"OWNERS ASSOC\w*",
    r"OWNERS'? ASS\w*",
    r"CONDOMINIUM ASS\w*",
    r"ASSOCIATION",
    r"ASSOC\.?",
    r"HABITAT FOR HUMANITY",
    r"HOUSING AUTHORITY",
    r"HOUSING TRUST",
    r"LAND TRUST",
    r"TOWN OF",
    r"TETON COUNTY",
    r"COUNTY OF",
    r"STATE OF",
    r"UNITED STATES",
    r"USA",
    r"SCHOOL DIST\w*",
    r"CHURCH",
    r"DIOCESE",
    r"SCHOOL",
    r"HOSPITAL",
    r"FOUNDATION",
    r"IMPROVEMENT (AND|&) SERVICE",
    r"WATER (AND|&) SEWER",
    r"ISD",
    r"DISTRICT",
    r"CONSERVATION",
    r"NATIONAL PARK",
])
BUSINESS = word_pattern([
    r"L\.?L\.?C\.?",
    r"L\.?C\.?",
    r"L\.?L\.?L\.?P\.?",
    r"L\.?L\.?P\.?",
    r"L\.?P\.?",
    r"INC\.?",
    r"INCORPORATED",
    r"CORP\.?",
    r"CORPORATION",
    r"COMPANY",
    r"CO\.",
    r"LTD\.?",
    r"LIMITED",
    r"HOLDINGS",
    r"PARTNERS",
    r"PARTNERSHIP",
    r"PROPERTIES",
    r"INVESTMENTS?",
    r"ENTERPRISES",
    r"VENTURES?",
    r"GROUP",
    r"CAPITAL",
    r"DEVELOPMENT",
    r"MANAGEMENT",
    r"ASSOCIATES",
    r"REALTY",
    r"EQUITIES",
    r"FUND",
])
STRONG_BIZ = word_pattern([
    r"L\.?L\.?C\.?",
    r"L\.?C\.?",
    r"INC\.?",
    r"INCORPORATED",
    r"CORP\.?",
    r"CORPORATION",
    r"COMPANY",
    r"CO\.",
    r"L\.?L\.?L\.?P\.?",
    r"L\.?L\.?P\.?",
    r"L\.?\s?P\.?",
    r"LTD\.?",
    r"LIMITED",
    r"PARTNERSHIP",
    r"PARTNERS",
])
TRUST = word_pattern([
    r"TRUSTS?",
    r"TRUSTEES?",
    r"REVOCABLE",
    r"IRREVOCABLE",
    r"TR\.",
    r"TRST",
    r"QPRT",
    r"U/?T/?A",
    r"U/?A/?D",
])


def classify(owner):
    text = (owner or "").upper()
    if not text.strip():
        return "blank"
    if "NAME WITHHELD" in text:
        return "name_withheld"
    text = re.split(r"\bC/O\b|\bC/0\b|\bATTN:?", text)[0]
    if NONPROFIT_GOV.search(text) and not re.search(r"(?<![A-Z])L\.?L\.?C", text):
        return "nonprofit_gov_hoa"
    is_business = bool(BUSINESS.search(text))
    is_trust = bool(TRUST.search(text))
    if is_trust and not STRONG_BIZ.search(text):
        return "trust"
    if is_business and is_trust:
        return "business_and_trust"
    if is_business:
        return "business"
    if is_trust:
        return "trust"
    if "," in text or re.match(r"^[A-Z'\- ]+\. [A-Z]", text):
        return "individual"
    return "unclassified_no_comma"


def before_care_of(owner):
    text = (owner or "").upper()
    return re.split(r"\bC/O\b|\bC/0\b|\bATTN:?", text)[0]


def pct(part, whole):
    if not whole:
        return None
    return round(100.0 * part / whole, 1)


def main():
    connection = sqlite3.connect(GPKG)
    rows = connection.execute(
        "select accountno, owner, owner_stat, accttype, taxyear, acctval, impsval "
        "from ownership"
    ).fetchall()
    residential = [row for row in rows if row[3] == "Residential"]
    taxyears = collections.Counter(row[4] for row in residential)
    no_improvement = sum(1 for row in residential if not row[6])

    entity_labels = {"trust", "business", "business_and_trust"}
    business_labels = {"business", "business_and_trust"}

    counts = collections.Counter()
    values = collections.Counter()
    total_value = 0
    entity_accounts = 0
    entity_value = 0
    business_accounts = 0
    business_value = 0
    high_accounts = 0
    high_entity = 0
    business_out = 0
    trust_accounts = 0
    trust_person_named = 0
    out_of_state_states = collections.Counter()

    for _account, owner, state, _accttype, _taxyear, acctval, _impsval in residential:
        label = classify(owner)
        value = acctval or 0
        counts[label] += 1
        values[label] += value
        total_value += value
        if label in entity_labels:
            entity_accounts += 1
            entity_value += value
        if label in business_labels:
            business_accounts += 1
            business_value += value
            state_code = (state or "").strip().upper()
            if state_code != "WY":
                business_out += 1
                out_of_state_states[state_code or "(blank)"] += 1
        if value >= 10_000_000:
            high_accounts += 1
            if label in entity_labels:
                high_entity += 1
        if label == "trust":
            trust_accounts += 1
            if "," in before_care_of(owner):
                trust_person_named += 1

    summary = {
        "source_url": "https://maps.terragis.net/tetonwy/mapserver/download/data/ownership.gpkg",
        "layer": "ownership",
        "universe": "accttype = 'Residential'",
        "value_field": "acctval as listed",
        "entity_labels": sorted(entity_labels),
        "business_labels_for_mailing": sorted(business_labels),
        "out_of_state_rule": "owner_stat != 'WY'; blank counts as out of state",
        "trust_person_named_rule": "owner text before C/O contains a comma",
        "residential_accounts": len(residential),
        "residential_with_no_improvement_value": no_improvement,
        "taxyear_counts": {str(key): taxyears[key] for key in taxyears},
        "total_acctval": total_value,
        "class_accounts": dict(counts),
        "class_acctval": dict(values),
        "entity_account_pct": pct(entity_accounts, len(residential)),
        "entity_value_pct": pct(entity_value, total_value),
        "business_account_pct": pct(business_accounts, len(residential)),
        "business_value_pct": pct(business_value, total_value),
        "high_value_accounts_acctval_at_least_10m": high_accounts,
        "high_value_entity_pct": pct(high_entity, high_accounts),
        "business_out_of_state_mailing_pct": pct(business_out, business_accounts),
        "business_out_of_state_top_states": out_of_state_states.most_common(8),
        "trust_accounts": trust_accounts,
        "trust_person_named_pct": pct(trust_person_named, trust_accounts),
    }
    SUMMARY.write_text(json.dumps(summary, indent=2) + "\n")
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()
