"""Count side-price fields for one bookmaker and player market in a saved /props page."""

import argparse
import json
import math
from pathlib import Path


def number(value):
    return type(value) is int or (type(value) is float and math.isfinite(value))


def side_price(value, odds_format):
    if value is None:
        return "missing"
    if number(value):
        if odds_format == "decimal" and value > 1:
            return "priced"
        if odds_format == "american" and abs(value) >= 100 and value % 1 == 0:
            return "priced"
    return "invalid"


def has_key(value):
    return isinstance(value, str) and bool(value.strip())


def count_page(entries, book, market, odds_format):
    if not isinstance(entries, list):
        raise ValueError("Expected the JSON array from a successful /props response.")
    counts = dict(both=0, over_only=0, under_only=0, neither=0, special_payout=0,
                  withdrawn=0, invalid_price=0, missing_price_fields=0)
    result = dict(saved_entries=len(entries), book_rows_in_page=0, empty_groups=0,
                  rows_missing_book_or_market=0, matching_rows=0, side_fields=counts,
                  matching_rows_with_zero_line=0, matching_rows_without_numeric_line=0)
    for entry in entries:
        if not isinstance(entry, dict) or "market_key" not in entry:
            raise ValueError("A page entry has no recognizable /props market field.")
        market_key = entry["market_key"]
        books = entry.get("books", [entry])
        if not isinstance(books, list):
            raise ValueError("Expected a list of book records inside each grouped entry.")
        if not books:
            result["empty_groups"] += 1
        for row in books:
            if not isinstance(row, dict):
                raise ValueError("A book record is not a JSON object.")
            result["book_rows_in_page"] += 1
            if not has_key(market_key) or not has_key(row.get("bookmaker")):
                result["rows_missing_book_or_market"] += 1
                continue
            if market_key != market or row["bookmaker"] != book:
                continue
            result["matching_rows"] += 1
            if not number(entry.get("line")):
                result["matching_rows_without_numeric_line"] += 1
            elif entry["line"] == 0:
                result["matching_rows_with_zero_line"] += 1

            if row.get("available") is False or row.get("action") == "remove":
                bucket = "withdrawn"
            elif (row.get("is_dfs_flat_payout") or row.get("dfs_normalized")
                  or row.get("payout_multiplier_scope") == "entry"):
                bucket = "special_payout"
            elif "over_price" not in row and "under_price" not in row:
                bucket = "missing_price_fields"
            else:
                over = side_price(row.get("over_price"), odds_format)
                under = side_price(row.get("under_price"), odds_format)
                if "invalid" in (over, under):
                    bucket = "invalid_price"
                elif over == under == "priced":
                    bucket = "both"
                elif over == "priced":
                    bucket = "over_only"
                elif under == "priced":
                    bucket = "under_only"
                else:
                    bucket = "neither"
            counts[bucket] += 1
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("file", type=Path, help="Saved HTTP 200 JSON array from /props")
    parser.add_argument("--book", required=True, help="Exact bookmaker key")
    parser.add_argument("--market", required=True, help="Exact market key")
    parser.add_argument("--odds-format", required=True, choices=("american", "decimal"),
                        help="Price format used for the saved request")
    args = parser.parse_args()
    try:
        with args.file.open(encoding="utf-8-sig") as source:
            summary = count_page(json.load(source), args.book, args.market, args.odds_format)
    except (OSError, ValueError, RecursionError) as error:
        parser.exit(2, "Could not read a /props page: " + str(error) + "\n")
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()
