import json
import requests
import sys

# ✅ ตั้งค่าให้ Python รองรับ UTF-8 (แก้ปัญหาภาษาไทยใน CMD)
sys.stdout.reconfigure(encoding='utf-8')

# ✅ URL ของ API (เปลี่ยนเป็น API จริงของคุณ)
API_URL = "http://localhost:4000/machines"  # 🔹 เปลี่ยน URL นี้ให้เป็น API ของคุณ

# ✅ ยิง API ด้วย requests
response = requests.get(API_URL)

# ✅ เช็กว่า API ตอบกลับสำเร็จหรือไม่ (status code 200)
if response.status_code == 200:
    parsed_data = response.json()  # แปลง JSON เป็น Python Dictionary
else:
    print(f"❌ ไม่สามารถดึงข้อมูลจาก API ได้ (Status Code: {response.status_code})")
    exit()

# ✅ วนลูปแสดงข้อมูลเครื่องจักรแบบละเอียด
for machine in parsed_data:
    print(f"\n🔹 เครื่องจักร: {machine['name']} (ID: {machine['machineID']})")
    print(f"   🔸 ประเภท: {machine['type']}")
    print(f"   🔸 สถานะ: {machine['status']}")
    print(f"   🔸 วันซ่อมบำรุงล่าสุด: {machine['lastMaintenanceDate'] if machine['lastMaintenanceDate'] else 'ไม่มีข้อมูล'}")
    print(f"   🔸 หมายเหตุ: {machine['notes'] if machine['notes'] else 'ไม่มีหมายเหตุ'}")
    
    # ✅ ตรวจสอบ Machine Details
    for detail in machine["machineDetails"]:
        print(f"\n   ─── Machine Detail ID: {detail['MachineDetailID']} ───")
        print(f"      ⚙️ กำลังการผลิต: {detail['outputRate']} หน่วย/ชม.")
        print(f"      ⏳ เวลาเปลี่ยนงาน: {detail['changOver']} นาที")
        
        # ✅ วนลูปแสดงสูตรการผลิตที่เครื่องจักรสามารถทำได้
        for recipe in detail["recipes"]:
            print(f"\n      🔹 สูตรการผลิต (Recipe ID: {recipe['recipeID']})")
            print(f"         ➤ ผลิต {recipe['outputQuantity']} {recipe['outputItemType']} (ID: {recipe['outputItemID']})")
            print("         📦 วัตถุดิบที่ใช้:")
            
            # ✅ วนลูปแสดงวัตถุดิบที่ใช้ในสูตร
            for ingredient in recipe["ingredients"]:
                material = ingredient["material"]
                print(f"            - {material['name']} ({material['description']})")
                print(f"              ➡️ ปริมาณ: {ingredient['quantityNeed']} {material['unit']}")

    print("\n" + "-"*60)