from appPublic.timeUtils import curDateString, dateAdd
from ahserver.serverenv import get_serverenv

async def set_program(request, program_type, quota, term=1):
	db = DBPools()
	dbname = get_serverenv('get_module_dbname')('rag')
	async with db.sqlorContext(dbname) as sor:
		u = await get_session_userinfo(request)
		sql="select * from ragquote where orgid = ${orgid}$ order by enabled_date"
		qs = await sor.sqlExe(sql, {'orgid': u.userorgid})
		if len(qs) == 0:
			today = curDateString()
			expired_date = dateadd(today, months=term)
			ns = {
				"id": uuid(),
				"orgid": u.userorgid,
				"enabled_date": today,
				"expired_date": expired_date,
				'quota': params_kw.quota
			}
			await sor.C('ragquota', ns)
		else:
			lastq = qs[-1]
			expired_date = dateadd(lastq.expired_date, months=term)
			ns = {
				"id": uuid(),
				"orgid": u.userorgid,
				"enabled_date": lastq.expired_date,
				"expired_date": expired_date,
				'quota': params_kw.quota
			}
			await sor.C('ragquota', ns)


async def get_rag_programs(request):
	db = DBPools()
	dbname = get_serverenv('get_module_dbanme')('rag')
	async with db.sqlorContext(dbname) as sor:
		recs = await sor.R('ragprogram', {})
		return recs
	return []

