import os, tempfile, io, datetime as dt
os.environ['ISTUDY_DB'] = os.path.join(tempfile.mkdtemp(), 't.db')
import app as A
c = A.app.test_client()
def j(r): return r.get_json()
def H(t): return {'Authorization': 'Bearer ' + t}
def test_flow():
    assert c.post('/api/auth/signup', json={'email': 'bad', 'password': 'password1', 'agree': True}).status_code == 400
    assert c.post('/api/auth/signup', json={'email': 'a@b.co', 'password': 'password1', 'agree': True, 'under18': True}).status_code == 400
    r = c.post('/api/auth/signup', json={'email': 'a@b.co', 'password': 'password1', 'agree': True}); assert r.status_code == 201
    t = j(r)['token']; h = H(t)
    assert c.post('/api/auth/signup', json={'email': 'a@b.co', 'password': 'password1', 'agree': True}).status_code == 409
    assert c.get('/api/courses').status_code == 401
    assert c.put('/api/profile', json={'name': 'Ada', 'step': 3, 'target_cgpa': 9}, headers=h).status_code == 400
    assert j(c.put('/api/profile', json={'name': 'Ada', 'step': 3, 'target_cgpa': 4.5}, headers=h))['profile']['step'] == 3
    cid = j(c.post('/api/courses', json={'code': 'eco 201', 'name': 'Microeconomics', 'units': 3}, headers=h))['id']
    g = j(c.get(f'/api/courses/{cid}/grades', headers=h)); aid = g['assessments'][0]['id']
    assert c.put(f'/api/assessments/{aid}', json={'score': 99}, headers=h).status_code == 400
    assert c.put(f'/api/assessments/{aid}', json={'score': 18}, headers=h).status_code == 200
    ex = j(c.get(f'/api/courses/{cid}/grades', headers=h))['assessments'][2]['id']
    s = j(c.get(f'/api/courses/{cid}/grades', headers=h))['summary']
    assert s['status'] == 'estimate' and s['percent'] == 60.0 and 'needed_message' in s
    c.put(f'/api/assessments/{ex}', json={'score': 30}, headers=h)
    for a in j(c.get(f'/api/courses/{cid}/grades', headers=h))['assessments'][1:2]:
        c.put(f"/api/assessments/{a['id']}", json={'score': 12}, headers=h)
    s = j(c.get(f'/api/courses/{cid}/grades', headers=h))['summary']
    assert s['final'] and s['percent'] == 60.0 and s['letter'] == 'B', s
    p = j(c.get('/api/progress', headers=h)); assert p['gpa']['cgpa'] == 4.0 and p['gpa']['status'] == 'confirmed'
    # other user cannot see it
    t2 = j(c.post('/api/auth/signup', json={'email': 'x@y.co', 'password': 'password1', 'agree': True}))['token']
    assert c.get(f'/api/courses/{cid}/grades', headers=H(t2)).status_code == 404
    # topics, home, plan
    tid = j(c.post(f'/api/courses/{cid}/topics', json={'name': 'Elasticity of demand', 'status': 'difficult', 'confidence': 2}, headers=h))['id']
    hm = j(c.get('/api/home', headers=h)); assert 'Elasticity of demand' in hm['focus']['text']
    assert j(c.post('/api/plan/generate', json={}, headers=h))['created'] >= 1
    assert c.post('/api/plan/add', json={'tid': tid}, headers=h).status_code == 200
    # timetable import / clash
    txt = 'Mon 08:00-10:00 ECO 201 Hall A\nMon 09:00-11:00 CSC 205 Lab\nWed 14:00-16:00 STA 211'
    it = j(c.post('/api/timetable/import', json={'text': txt}, headers=h))['items']
    assert len(it) == 3 and 'Clash' in it[0]['flags'] and 'Check venue' in it[2]['flags'] and 'New course' in it[1]['flags']
    assert c.post('/api/timetable/import', json={'text': 'nothing'}, headers=h).status_code == 422
    assert j(c.post('/api/timetable/confirm', json={'items': it}, headers=h))['saved'] == 3
    assert len(j(c.get('/api/timetable', headers=h))['clashes']) == 1
    # deadline + planner
    d = (dt.date.today() + dt.timedelta(days=3)).isoformat()
    assert c.post('/api/deadlines', json={'title': 'Test 1', 'kind': 'test', 'due': d, 'cid': cid}, headers=h).status_code == 201
    pl = j(c.get(f'/api/planner?from={dt.date.today()}&to={d}', headers=h)); assert len(pl['days']) == 4
    # materials, quiz, tutor
    notes = ("Elasticity of demand measures how much the quantity demanded responds to a change in price. Demand is elastic when quantity demanded changes by a larger percentage than price. "
             "Demand is inelastic when quantity demanded changes by a smaller percentage than price. Price elasticity depends on substitutes, necessity and time. "
             "A good with many substitutes has elastic demand because consumers can switch easily. Necessities such as medicine usually have inelastic demand. "
             "Total revenue rises when price increases if demand is inelastic. Total revenue falls when price increases if demand is elastic.")
    mid = j(c.post(f'/api/courses/{cid}/materials', json={'name': 'Notes', 'text': notes}, headers=h))['id']
    m = j(c.get(f'/api/materials/{mid}', headers=h)); assert m['summary'] and m['concepts'] and m['flashcards']
    q = j(c.post('/api/quiz/generate', json={'cid': cid, 'n': 3}, headers=h))['questions']; assert q and q[0]['options'][q[0]['answer']]
    r = j(c.post('/api/tutor/chat', json={'message': 'Explain elasticity of demand'}, headers=h)); assert r['meta']['mode'] == 'offline' and 'notes' in r['reply'].lower() and r['meta']['tid'] == tid
    assert c.post('/api/quiz/result', json={'cid': cid, 'score': 2, 'total': 3}, headers=h).status_code == 200
    # privacy: personalisation off removes record-based context
    c.put('/api/settings', json={'ai_personalisation': False}, headers=h)
    r = j(c.post('/api/tutor/chat', json={'message': 'What should I study today?'}, headers=h)); assert 'tid' not in r['meta']
    assert 'Progress report' in j(c.get('/api/progress/report', headers=h))['text']
    assert 'courses' in j(c.get('/api/export', headers=h))
    assert c.delete('/api/account', headers=h).status_code == 200 and c.get('/api/me', headers=h).status_code == 401
if __name__ == '__main__': test_flow(); print('ALL BACKEND TESTS PASSED')
