#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# freecadcmd freesim.py freecad1.stp cikti.png
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\freecad1.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
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}")

# ------------------------------------------------------------
# 🔹 GIF — önce sağdan sola (Y ekseni), sonra yukarı-aşağı (X ekseni) tam tur
# ------------------------------------------------------------
debug("🎞️ GIF oluşturuluyor: sağ-sol dönüş + yukarı-aşağı tam tur...")

frames = []
num_frames = 36
angle_step = 10
pause_duration = 1.5  # dönüşler arası bekleme süresi (saniye)

# 🔸 1. Dönüş: sağdan sola (Y ekseni)
debug("➡️ 1. Dönüş: sağdan sola (Y ekseni)")
for i in range(num_frames):
    yaw = i * angle_step
    rotation = FreeCAD.Rotation(Base.Vector(0, 1, 0), yaw)
    view.setCameraOrientation(rotation)
    view.fitAll()
    FreeCADGui.updateGui()
    time.sleep(0.1)
    frame_file = os.path.join(output_dir, f"yaw_{i:02d}.png")
    view.saveImage(frame_file, 1280, 720, "White")
    frames.append(frame_file)
    debug(f"Frame {i+1}/{num_frames} (YAW)")

# 🔸 Duraklama (hareketsiz birkaç frame)
debug("⏸️ Dönüşler arası duraklama...")
for i in range(int(pause_duration / 0.1)):
    frame_file = os.path.join(output_dir, f"pause_{i:02d}.png")
    view.saveImage(frame_file, 1280, 720, "White")
    frames.append(frame_file)
time.sleep(pause_duration)

# 🔸 2. Dönüş: yukarıdan aşağıya (X ekseni) tam tur
debug("↕️ 2. Dönüş: yukarıdan aşağıya (X ekseni, tam tur)")
for i in range(num_frames):
    pitch = i * angle_step  # 0 → 360° tam tur
    rotation = FreeCAD.Rotation(Base.Vector(1, 0, 0), pitch)
    view.setCameraOrientation(rotation)
    view.fitAll()
    FreeCADGui.updateGui()
    time.sleep(0.1)
    frame_file = os.path.join(output_dir, f"pitch_{i:02d}.png")
    view.saveImage(frame_file, 1280, 720, "White")
    frames.append(frame_file)
    debug(f"Frame {i+1}/{num_frames} (PITCH)")

# 🔹 GIF oluştur
gif_path = os.path.join(output_dir, "rotation_yaw_then_pitch_full.gif")
try:
    images = [imageio.imread(f) for f in frames if os.path.exists(f)]
    imageio.mimsave(gif_path, images, duration=0.08, loop=0, subrectangles=True)
    debug(f"✅ 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ı.")
