import sys, threading, tempfile, pathlib, json, urllib.request, urllib.error, base64
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
import server
server.DB=pathlib.Path(tempfile.mkdtemp())/'test.sqlite3'; server.init()
s=server.ThreadingHTTPServer(('127.0.0.1',0),server.Handler); threading.Thread(target=s.serve_forever,daemon=True).start(); url=f'http://127.0.0.1:{s.server_port}'
def post(data,role='Síndico'):
    req=urllib.request.Request(url+'/api/action',data=json.dumps(data).encode(),headers={'Content-Type':'application/json','X-Demo-Role':role}); return json.load(urllib.request.urlopen(req))
def state():return json.load(urllib.request.urlopen(url+'/api/state'))
assert len(state()['projects'])==5
pid=post(dict(op='create',title='Teste',category='Hidráulica',location='Bloco 1',description='Teste',priority='Normal',budget=1000,deadline='2026-12-30'))['project_id']
for i in range(3): post(dict(op='proposal',project_id=pid,supplier=f'Empresa {i}',value=1000+i*100,days=3,warranty=12,scope='Reparo',payment='À vista'),'Prestador')
q=next(q for q in state()['proposals'] if q['project_id']==pid)
post(dict(op='approve',project_id=pid,proposal_id=q['id'],justification='Melhor condição'))
post(dict(op='start',project_id=pid,start='2026-11-25'))
post(dict(op='progress',project_id=pid,progress=50,actual=500,detail='Metade concluída'))
post(dict(op='attachment',project_id=pid,title='Evidência',kind='Documento',filename='teste.txt',data=base64.b64encode(b'teste').decode()))
a=next(a for a in state()['attachments'] if a['project_id']==pid); assert urllib.request.urlopen(url+'/api/file/'+str(a['id'])).read()==b'teste'
post(dict(op='finance',project_id=pid,title='Pagamento teste',type='Despesa',value=1000,date='2026-11-25'))
post(dict(op='finish',project_id=pid,completed='2026-11-26',actual=1000,detail='Vistoria concluída'))
p=next(p for p in state()['projects'] if p['id']==pid);assert p['stage']=='Concluído' and p['progress']==100
try:post(dict(op='start',project_id=pid,start='2026-11-25'),'Morador');raise AssertionError('acesso indevido')
except urllib.error.HTTPError as e:assert e.code==403
print('API: fluxo completo, download e bloqueio de edição pelo perfil Morador OK')

s.shutdown()
s.server_close()
