#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import json
import sqlite3
import matplotlib.pyplot as plt


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument('db', type=str, metavar='DB',
                        help='The sqlite database file')
    parser.add_argument('-s', '--season', type=int, required=False,
                        help='The season to use')
    args = parser.parse_args()

    cnx = sqlite3.connect(args.db)
    cur = cnx.cursor()
    cur.execute("SELECT year, avnr FROM payment_variant WHERE NOT test_variant ORDER BY year, avnr")
    payment_vars = cur.fetchall()
    if args.season:
        payment_vars = [p for p in payment_vars if p[0] == args.season]
    cur.execute("SELECT data FROM payment_variant WHERE (year, avnr) = (?, ?)", payment_vars[-1])
    data = json.loads(cur.fetchall()[0][0])
    az_sort = data['AuszahlungSorten']
    curves = [{n: d for n, d in enumerate(c)} for c in az_sort['Kurven']]
    c_sort_idx = [sum(c.values()) / len(c) for c in curves]
    c_sort = sorted([i for i in range(len(curves))], key=lambda a: c_sort_idx[a])[::-1]
    c_sort_2 = {c: i for i, c in enumerate(c_sort)}

    names: list[list[str]] = [[] for c in curves]
    for sortid, d1 in az_sort.items():
        if len(sortid) != 2:
            continue
        for attrid, d2 in d1.items():
            for geb, d3 in d2.items():
                names[c_sort_2[d3]].append(f'{sortid}/{attrid}/{geb}')

    title = f'Endabrechnung {payment_vars[-1][0]}'
    plt.figure(num=title)
    plt.title(title)
    for i in c_sort:
        c = curves[i]
        plt.plot(c.keys(), c.values())
    plt.legend(['\n'.join(a) for a in names], fontsize=8)
    plt.xlabel('Gradation [°Oe]')
    plt.ylabel('Betrag [€/kg]')
    plt.vlines([55, 68, 73, 84], 0.0, 1.5, colors='black')
    plt.xlim([50, 120])
    plt.ylim([0.0, 1.5])
    plt.grid(linestyle='--')
    plt.show()


if __name__ == '__main__':
    main()