#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys, os, time, math

# 🔹 FreeCAD modülleri yükleniyor
FREECAD_PATH = r"D:\__sistem__\ProgramFiles\FreeCAD\bin"
if FREECAD_PATH not in sys.path:
    sys.path.append(FREECAD_PATH)

import FreeCAD
from FreeCAD import Base

# 🔹 GUI yükle
try:
    import FreeCADGui
    FreeCADGui.showMainWindow()
    print("[DEBUG] ✅ FreeCAD GUI başarıyla yüklendi.", flush=True)
except Exception as e:
    print(f"[DEBUG] ❌ FreeCADGui yüklenemedi: {e}", flush=True)

import ImportGui
import imageio.v2 as imageio

def debug(msg):
    print(f"[DEBUG] {msg}", flush=True)

debug("🚀 Script başlatıldı")

input_file = r"D:\__sistem__\ProgramFiles\FreeCAD\bin\freecad.stp"
output_dir = r"D:\__sistem__\ProgramFiles\FreeCAD\bin"
base_name = "cikti"

if not os.path.exists(input_file):
    debug("❌ Girdi dosyası yok.")
    sys.exit(1)

# 🔹 Doküman oluştur
doc = FreeCAD.newDocument("AutoRender")
debug("🆕 Yeni belge oluşturuldu.")

# 🔹 STEP içe aktar
ImportGui.insert(input_file, doc.Name)
debug("📦 STEP dosyası içe aktarıldı.")

# 🔹 Görünüm ayarla
FreeCADGui.showMainWindow()
FreeCADGui.ActiveDocument = FreeCADGui.getDocument(doc.Name)
view = FreeCADGui.ActiveDocument.ActiveView
view.viewAxonometric()
view.fitAll()
FreeCADGui.updateGui()
debug("🎨 Model görüntülendi (renkli).")

# 🔹 PNG kayıt (opsiyonel)
output_file = os.path.join(output_dir, f"{base_name}_1.png")
view.saveImage(output_file, 1920, 1080, "White")
debug(f"📸 Görüntü kaydedildi: {output_file}")

# ------------------------------------------------------------
# 🔹 Gelişmiş Spiral 3D loop GIF — yaw + pitch + kendi ekseni
# ------------------------------------------------------------
debug("🎞️ Gelişmiş Spiral 3D loop GIF oluşturuluyor...")

frames = []
num_frames_per_loop = 144   # daha fazla frame → daha akıcı ve detaylı
num_loops = 2
yaw_step = 360 / num_frames_per_loop
pitch_amplitude = 60        # dikey hareketi arttır
spin_amplitude = 30         # kendi ekseni etrafındaki hafif dönüş
duration_per_frame = 0.06

for loop in range(num_loops):
    for i in range(num_frames_per_loop):
        # Yaw: tam 360° sağ-sol
        yaw = i * yaw_step
        # Pitch: sinüs ile yukarı-aşağı hareket
        pitch = pitch_amplitude * math.sin(math.radians(i * (360 / num_frames_per_loop)))
        # Hafif kendi ekseni (Z ekseni) dönüşü ekle
        spin = spin_amplitude * math.sin(math.radians(i * (360 / num_frames_per_loop)))
        rotation = (FreeCAD.Rotation(Base.Vector(0, 0, 1), spin) *
                    FreeCAD.Rotation(Base.Vector(1, 0, 0), pitch) *
                    FreeCAD.Rotation(Base.Vector(0, 1, 0), yaw))
        view.setCameraOrientation(rotation)
        view.fitAll()
        FreeCADGui.updateGui()
        time.sleep(0.03)  # frame hızını arttırmak için azaltıldı
        frame_file = os.path.join(output_dir, f"spiral_full_{loop}_{i:03d}.png")
        view.saveImage(frame_file, 1280, 720, "White")
        frames.append(frame_file)
        debug(f"Loop {loop+1}/{num_loops}, Frame {i+1}/{num_frames_per_loop}")

# 🔹 GIF oluştur
gif_path = os.path.join(output_dir, "rotation_spiral_full.gif")
try:
    images = [imageio.imread(f) for f in frames if os.path.exists(f)]
    imageio.mimsave(gif_path, images, duration=duration_per_frame, loop=0)  # sürekli loop
    debug(f"✅ Gelişmiş Spiral loop GIF oluşturuldu: {gif_path}")
except Exception as e:
    debug(f"[HATA] GIF oluşturulamadı: {e}")

debug("🏁 Tüm işlem başarıyla tamamlandı.")
