# pie_chart_python.py
# September - 2026
# RJM Programming
# Thanks to https://www.w3schools.com/python/default.asp

import os
import matplotlib
import sys

# Set backend to Agg before importing pyplot
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

import numpy as np
#import plotly.express as px
from PIL import Image

nums = []
lbls = []
mytitle = ""
sofar = 0
place = ''
midsuff = ''
if len(sys.argv) > 1:
  place = sys.argv[-1 + len(sys.argv)]

if len(sys.argv) > 2:
  midsuff = sys.argv[-2 + len(sys.argv)].replace('piechartpython','').replace('.py','')

if len(nums) <= 0:
  while sofar < 100:
     print(f"Enter your percentage value regarding a pie chart where so far {sofar} has already been allocated.  Can append after a comma a pie chart sector label.")
     anum = input()
     if "," in anum:
       x = anum.split(",")
       nums.append(int(x[0]))
       sofar += int(x[0])
       lbls.append(anum.replace(x[0] + ',', ''))
     else:
       nums.append(int(anum))
       lbls.append('')
       sofar += int(anum)
  

y = np.array(nums)

fig, ax = plt.subplots()

if len(mytitle) > 0:
  plt.title(mytitle)

if len(lbls) < len(nums):
  ax.pie(y, autopct="%1.1f%%")
else:
  ax.pie(y, labels=lbls)

fig.savefig(place + "plot" + midsuff + ".png", bbox_inches="tight")


# 1. Load the image
img = mpimg.imread(place + 'plot' + midsuff + '.png')

# 2. Process or manipulate the image (Optional)
# For example, let's look at the shape or apply changes
#print(f"Image shape: {img.shape}")

# 3. Create the plot without displaying it
plt.imshow(img)
plt.axis('off')  # Hide axis lines and labels

# 4. Save the result to a file instead of showing it
plt.savefig(place + 'output_image' + midsuff + '.png', bbox_inches='tight', pad_inches=0)
plt.close()


# Open the PNG image file
with Image.open(place + "plot" + midsuff + ".png") as img:
    # Display the image using your system's default viewer
    img.show()
    
    # Optional: Load the data into memory so you can safely close the file
    img.load() 


exit()


  
