import io
from pathlib import Path
import pandas as pd
import qrcode
import streamlit as st
st.set_page_config(page_title='AIMPACT | QR Asset Tracker',page_icon='🏷️',layout='wide')
st.title('🏷️ QR Equipment Tracker')
st.caption('Local teaching demo • Synthetic equipment • QR encodes an asset ID, not a public maintenance database')
FILE=Path(__file__).with_name('sample_assets.csv')
df=pd.read_csv(FILE,dtype=str).fillna('')
if 'history' not in st.session_state:st.session_state.history=[]
asset=st.selectbox('Select equipment',df.asset_id.tolist(),format_func=lambda x:f'{x} — {df.loc[df.asset_id==x,"equipment"].iloc[0]}')
record=df[df.asset_id==asset].iloc[0]
a,b=st.columns([1,2]);
with a:
 qr=qrcode.make('AIMPACT-DEMO-ASSET:'+asset);buf=io.BytesIO();qr.save(buf,format='PNG');st.image(buf.getvalue(),caption='Scan to read the demo asset identifier');st.download_button('Download QR PNG',buf.getvalue(),asset+'.png','image/png')
with b:
 st.subheader(record.equipment);st.metric('Asset ID',asset);st.write('Location:',record.location);st.write('Maintenance status:',record.status)
 st.write('Last inspection:',record.last_inspection)
st.subheader('Add inspection note (session only)')
with st.form('note'):
 inspector=st.text_input('Inspector / initials',max_chars=80)
 note=st.text_area('Observation',max_chars=500)
 submitted=st.form_submit_button('Add local note')
 if submitted and inspector.strip() and note.strip():
  st.session_state.history.append({'asset_id':asset,'inspector':inspector.strip(),'observation':note.strip()})
  st.success('Added to this browser session. Not stored on a shared server.')
st.dataframe(pd.DataFrame(st.session_state.history),use_container_width=True)
if st.session_state.history:st.download_button('Export session notes CSV',pd.DataFrame(st.session_state.history).to_csv(index=False).encode(),'inspection_notes.csv','text/csv')
st.warning('For real multi-user QR maintenance history, add authenticated hosting, durable storage and access controls. The QR itself contains only an identifier.')
