import matplotlib.pyplot as plt
from matplotlib.table import Table
from .utils import PLANET_SYMBOLS

# Podział znaków na żywioły i jakości (kolejność zodiakalna: 0–11)
ELEMENTS = ['FIR', 'EAR', 'AIR', 'WAT']
MODES = ['CAR', 'FIX', 'MUT']
SIGN_TO_ELEMENT = ['FIR', 'EAR', 'AIR', 'WAT'] * 3
SIGN_TO_MODE = ['CAR', 'FIX', 'MUT'] * 4

def plot_element_mode_table(horoscope):
    # Przygotuj siatkę: (element, modality) -> lista planet
    table = {el: {mo: [] for mo in MODES} for el in ELEMENTS}

    for planet, data in horoscope.positions.items():
        deg = data['longitude']
        sign_index = int(deg // 30)
        element = SIGN_TO_ELEMENT[sign_index]
        mode = SIGN_TO_MODE[sign_index]
        symbol = PLANET_SYMBOLS.get(planet, planet)
        table[element][mode].append(symbol)

    fig, ax = plt.subplots(figsize=(5, 4))
    ax.set_axis_off()

    # Utwórz tabelę
    tbl = Table(ax, bbox=[0, 0, 1, 1])

    # Nagłówki kolumn
    col_labels = [''] + MODES
    row_labels = ELEMENTS
    ncols = len(col_labels)
    nrows = len(row_labels) + 1

    cell_w, cell_h = 1.0 / ncols, 1.0 / nrows

    # Wiersz nagłówka
    for j, text in enumerate(col_labels):
        tbl.add_cell(0, j, width=cell_w, height=cell_h, text=text, loc='center', facecolor='lightgray')

    # Komórki + etykiety wierszy
    for i, el in enumerate(row_labels, start=1):
        tbl.add_cell(i, 0, width=cell_w, height=cell_h, text=el, loc='center', facecolor='lightgray')
        for j, mo in enumerate(MODES, start=1):
            planets = ' '.join(table[el][mo])
            tbl.add_cell(i, j, width=cell_w, height=cell_h, text=planets, loc='center')

    ax.add_table(tbl)
    ax.set_title("Żywioły i modalności", pad=20)

    plt.show()
