"""Offline comparison of invented equal-work jobs and prices. Python 3."""
import hashlib
import json
import platform
from datetime import datetime, timezone
from pathlib import Path


def count(value):
    if type(value) is not int or value < 0:
        raise ValueError("Counts and prices in cents must be nonnegative integers")
    return value


def evaluate(hours, capacity, fee, unit_price):
    if not isinstance(hours, list) or not hours:
        raise ValueError("Supply one count per hour, including zero-demand hours")
    capacity, fee, unit_price = map(count, (capacity, fee, unit_price))
    ledger = []
    for hour, jobs in enumerate(hours, start=1):
        covered = min(count(jobs), capacity)
        ledger.append(dict(hour=hour, jobs=jobs, covered=covered,
                           unused=capacity-covered, overflow=jobs-covered))
    demand = sum(hours)
    covered = sum(row["covered"] for row in ledger)
    fixed = len(hours) * fee
    overflow = demand - covered
    baseline = demand * unit_price
    mixed = fixed + overflow * unit_price
    return dict(hourly=ledger, jobs=demand, covered=covered, overflow=overflow,
                unused=len(hours)*capacity-covered, fixed_cents=fixed,
                overflow_cents=overflow*unit_price, all_on_demand_cents=baseline,
                mixed_cents=mixed, mixed_minus_on_demand_cents=mixed-baseline)


def main():
    fixture = Path(__file__).with_name("fixture.json")
    inputs = json.loads(fixture.read_text())
    params = [inputs[key] for key in ("capacity_jobs_per_hour",
              "capacity_fee_cents_per_hour", "on_demand_cents_per_job")]
    results = {}
    for trace in inputs["traces"]:
        result = evaluate(trace["hourly_jobs"], *params)
        if (result["covered"], result["mixed_cents"]) != (
                trace["expected_covered"], trace["expected_mixed_cents"]):
            raise ValueError(f"Fixture expectation failed for {trace['name']}")
        results[trace["name"]] = result
    record = {
        "executed_utc": datetime.now(timezone.utc).isoformat(),
        "python": platform.python_version(),
        "sha256": {p.name: hashlib.sha256(p.read_bytes()).hexdigest()
                   for p in (fixture, Path(__file__))},
        "results": results
    }
    print(json.dumps(record, indent=2))


if __name__ == "__main__":
    main()
