import streamlit as st
import matplotlib.pyplot as plt
import math

st.title("أداة رسم المخططات بالقياسات والإزاحة")

# تهيئة الذاكرة
if 'points' not in st.session_state:
    # كل نقطة: {from, dist, bearing}
    st.session_state.points = []

# زر لإضافة مسار جديد
if st.button("إضافة مسار جديد +"):
    st.session_state.points.append({'from': 0, 'dist': 0.0, 'bearing': 0.0})

# حقول الإدخال
st.subheader("أدخل المسافات والزوايا:")
for i, p in enumerate(st.session_state.points):
    st.markdown(f"**المسار {i+1}**")
    col1, col2, col3 = st.columns(3)
    with col1:
        # عدد النقاط الفعلي = len(points)
        num_existing = len(st.session_state.points)
        # يمكن اختيار من نقطة 1 إلى (عدد المسارات + 1)
        max_pt = num_existing + 1
        p['from'] = st.selectbox(
            "من نقطة",
            options=list(range(1, max_pt + 1)),
            index=min(p['from'], max_pt - 1),
            key=f"from_{i}"
        )
    with col2:
        p['dist'] = st.number_input(f"المسافة (م)", min_value=0.0, value=p['dist'], key=f"d_{i}", format="%.2f")
    with col3:
        p['bearing'] = st.number_input(f"الدرجة", min_value=0.0, max_value=360.0, value=p['bearing'], key=f"b_{i}", format="%.1f")

# رسم المخطط
if st.button("🎯 رسم المخطط"):
    # حساب الإحداثيات: النقطة 1 دائماً عند (0,0)
    coords = [(0.0, 0.0)]
    
    for i, p in enumerate(st.session_state.points):
        from_idx = p['from'] - 1  # تحويل إلى index (0-based)
        # التأكد من أن النقطة المصدر موجودة
        if from_idx >= len(coords):
            from_idx = len(coords) - 1
        fx, fy = coords[from_idx]
        
        # تحويل درجة البوصلة إلى إحداثيات
        angle_rad = math.radians(90 - p['bearing'])
        dx = p['dist'] * math.cos(angle_rad)
        dy = p['dist'] * math.sin(angle_rad)
        
        coords.append((fx + dx, fy + dy))
    
    xs = [c[0] for c in coords]
    ys = [c[1] for c in coords]
    
    fig, ax = plt.subplots(figsize=(10, 8))
    ax.set_facecolor("#fafafa")
    
    # رسم كل مسار بلون مختلف
    colors = plt.cm.tab10.colors
    for i, p in enumerate(st.session_state.points):
        from_idx = p['from'] - 1
        if from_idx >= len(coords) - 1:
            from_idx = len(coords) - 2
        fx, fy = coords[from_idx]
        tx, ty = coords[i + 1]
        c = colors[i % len(colors)]
        ax.plot([fx, tx], [fy, ty], "-o", color=c, linewidth=2, markersize=6, zorder=3)
        # سهم
        ax.annotate("", xy=(tx, ty), xytext=(fx, fy),
                    arrowprops=dict(arrowstyle="->", color=c, lw=1.5, alpha=0.7))
        # درجة البوصلة
        midx, midy = (fx + tx) / 2, (fy + ty) / 2
        ax.text(midx, midy, f"{p['bearing']}°", fontsize=9, color="#2ca02c",
                fontweight="bold",
                bbox=dict(boxstyle="round,pad=0.2", facecolor="white", alpha=0.7))
        # تسمية المسار
        ax.text(midx, midy - 0.8, f"{from_idx+1}←{i+2}", fontsize=7, color="#666", ha="center")
    
    # ترقيم النقاط
    for i in range(len(coords)):
        color, marker = ("green", "s") if i == 0 else ("#d62728", "o")
        size = 12 if i == 0 else 8
        ax.plot(coords[i][0], coords[i][1], marker, color=color, markersize=size, zorder=5)
        ax.annotate(str(i + 1), (coords[i][0], coords[i][1]),
                    textcoords="offset points", xytext=(10, 10),
                    fontsize=11, fontweight="bold", color=color,
                    bbox=dict(boxstyle="circle,pad=0.3", facecolor="white", edgecolor=color, lw=1.5))
    
    # بوصلة
    ax.annotate("N", xy=(0, 1), xytext=(0, 1.06), xycoords="axes fraction",
                fontsize=14, fontweight="bold", color="black", ha="center",
                arrowprops=dict(arrowstyle="->", color="black", lw=2))
    
    ax.set_aspect("equal")
    ax.grid(True, alpha=0.3, linestyle="--")
    ax.set_xlabel("X (متر)")
    ax.set_ylabel("Y (متر)")
    st.pyplot(fig)
else:
    st.info("👈 أضف مسارات من الزر أعلاه. أول نقطة عند (0,0)")
