import matplotlib.pyplot as plt
import numpy as np
from .utils import PLANET_SYMBOLS, calculate_aspects, ASPECTS

def plot_aspect_triangle(horoscope, save_path=None):
    planets = list(horoscope.positions.keys())
    n = len(planets)
    planet_idx = {planet: i for i, planet in enumerate(planets)}

    # Zamiana nazw na symbole
    labels = [PLANET_SYMBOLS.get(p, p) for p in planets]

    fig, ax = plt.subplots(figsize=(n * 0.5, n * 0.5))
    ax.set_xlim(-1, n)
    ax.set_ylim(n, -1)  # odwrócona oś Y

    # Aspekty
    aspects = calculate_aspects(horoscope.positions, ASPECTS)
    aspect_symbols = {
        'Conjunction': '☌',
        'Opposition': '☍',
        'Trine': '▲',
        'Square': '■',
        'Sextile': '*',
        'Semisextile': '∠',
        'Quincunx': '↷',
    }

    for p1, p2, name, color in aspects:
        i = planet_idx.get(p2)
        j = planet_idx.get(p1)
        if i is None or j is None:
            continue

        # tylko dolna część macierzy
        if i > j:
            y, x = i, j
        elif j > i:
            y, x = j, i
        else:
            continue

        glyph = aspect_symbols.get(name, '?')
        ax.text(x, y, glyph, fontsize=14, ha='center', va='center', color=color)
    # Rysowanie siatki dolnej trójkątnej
    for i in range(n):
        for j in range(i):
            ax.plot([j - 0.5, j + 0.5], [i - 0.5, i - 0.5], color='lightgray', linewidth=0.5)  # pozioma
            ax.plot([j - 0.5, j - 0.5], [j - 0.5, i + 0.5], color='lightgray', linewidth=0.5)  # pionowa

    # Etykiety
    for i, label in enumerate(labels):
        ax.text(-1.2, i, label, va='center', ha='right', fontsize=12)  # oś Y
        ax.text(i, n + 0.5, label, va='bottom', ha='center', fontsize=12, rotation=90)  # oś X

    # Wyłącz osie i ramkę
    ax.axis('off')
    
    

    if save_path:
        plt.savefig(save_path, bbox_inches='tight', dpi=300)
    else:
        plt.show()


