import hashlib
import hmac
import logging
import mimetypes
import re
import time
from contextlib import closing
from email.parser import BytesParser
from email.policy import default
from html import escape
from http.cookies import SimpleCookie
from urllib.parse import urlencode, parse_qs

from core import *
import gateway
import sms
from workbook import workbook_to_csv
from screens import render_admin, render_store, render_setup, render_login, render_invoice, render_error, product_label

NAV = {
    'Overview': {'dashboard':'Overview','pos':'Point of sale','orders':'Online orders'},
    'Inventory': {'catalog':'Medicine catalog','generics':'Generic directory','inventory':'Batch inventory','purchases':'Purchases','suppliers':'Suppliers'},
    'Management': {'reports':'Accounts & reports','tickets':'Support & complaints','settings':'Store & delivery','staff':'Staff accounts','audit':'Activity log'}
}
PERMISSIONS = {
    'owner': {key for group in NAV.values() for key in group}|{'rx','invoice','backup'},
    'manager': {'dashboard','pos','orders','catalog','generics','inventory','purchases','suppliers','reports','tickets','audit','invoice'},
    'pharmacist': {'dashboard','pos','orders','catalog','generics','inventory','tickets','rx','invoice'},
    'cashier': {'dashboard','pos','invoice'},
    'storekeeper': {'dashboard','inventory','purchases','suppliers'},
    'accountant': {'dashboard','purchases','suppliers','reports','invoice'},
    'order_desk': {'dashboard','orders','tickets','invoice'}
}

def esc(value):
    return escape(str(value if value is not None else ''),quote=True)

def hash_password(password):
    salt=secrets.token_hex(16)
    digest=hashlib.scrypt(password.encode(),salt=bytes.fromhex(salt),n=16384,r=8,p=1)
    return salt+'$'+digest.hex()

def password_valid(password, stored):
    salt,_,expected=stored.partition('$')
    digest=hashlib.scrypt(password.encode(),salt=bytes.fromhex(salt),n=16384,r=8,p=1)
    return hmac.compare_digest(digest.hex(),expected)

def create_user(db,data,role):
    username=field(data,'username',48,True).lower()
    if not re.fullmatch(r'[a-z0-9][a-z0-9_.-]{2,47}',username):
        raise Invalid('Use 3–48 letters, digits, periods, hyphens or underscores for username.')
    password=field(data,'password',128,True)
    if len(password)<12:
        raise Invalid('Use a password of at least 12 characters.')
    registration=field(data,'registration',70,role=='pharmacist')
    return db.execute('INSERT INTO users(username,password,name,role,registration) VALUES(?,?,?,?,?)',
        (username,hash_password(password),field(data,'name',90,True),role,registration)).lastrowid

def seed_demo(db,actor):
    db.execute("UPDATE settings SET value='demo' WHERE key='mode'")
    db.execute("INSERT INTO zones(name,fee,eta,branch_id) VALUES('Dhaka pilot zone',6000,'1–2 business days',1)")
    supplier=db.execute("INSERT INTO suppliers(name,phone,address) VALUES('Pilot Healthcare Supplies','01000000000','Dhaka')").lastrowid
    samples=[
      ('AST-DEMO-001','Digital Thermometer','ডিজিটাল থার্মোমিটার','Digital thermometer','Medical Devices','1 pc','unit','general','245','275'),
      ('AST-DEMO-002','Sterile Gauze Pack','স্টেরাইল গজ','Sterile gauze','Health Essentials','1 pack','pack','general','48','55'),
      ('AST-DEMO-003','Gentle Baby Wipes','বেবি ওয়াইপস','Baby wipes','Baby Care','60 wipes','pack','general','139','165'),
      ('AST-DEMO-004','Daily Care Face Wash','ফেস ওয়াশ','Face wash','Personal Care','100 ml','bottle','general','229','250'),
      ('AST-DEMO-RX','Practice Rx Tablet','টেস্ট ট্যাবলেট','Fictional training ingredient','Medicine','10 units','strip','rx','56','60'),
    ]
    from datetime import timedelta
    for index,(sku,brand,bn,generic,category,pack,unit,cl,price,mrp) in enumerate(samples,1):
        p=product_data(dict(sku=sku,brand=brand,brand_bn=bn,generic=generic,category=category,pack=pack,sale_unit=unit,
          classification=cl,mrp=mrp,price=price,maker='Training catalog',verified=1,online=1,source='Demo',dar='TRAINING ONLY' if cl=='rx' else '',
          form='Tablet' if cl=='rx' else '', strength='Demo' if cl=='rx' else ''))
        save_product(db,p)
        pid=one(db,'SELECT id FROM products WHERE sku=?',(sku,))['id']
        receive(db,dict(branch=1,supplier=supplier,reference='PILOT-01',expiry=(datetime.now(TZ).date()+timedelta(days=35 if index==2 else 360)).isoformat(),
                        lot=f'PILOT-{index:02}',product=pid,quantity=8 if index==2 else 40,cost=str(Decimal(price)*Decimal('.7')),shelf=f'A-{index}'),actor)
    for sku,form,strength,pack,link in (
          ('REF-NAPA-500-SUP','Suppository','500 mg','4 × 5','https://medex.com.bd/brands/23402/napa-500-mg-suppository'),
          ('REF-NAPA-120-SYR','Syrup','120 mg/5 ml','60 ml bottle','https://medex.com.bd/brands/28439/napa-120-mg-syrup')):
        save_product(db,product_data(dict(sku=sku,brand='Napa',brand_bn='নাপা',generic='Paracetamol',generic_bn='প্যারাসিটামল',
                    maker='Beximco Pharmaceuticals PLC',category='Medicine',form=form,strength=strength,pack=pack,sale_unit='unit',
                    classification='pending',price=0,mrp=0,source='MedEx reference',source_url=link)))

class Request:
    def __init__(self,environ,db):
        self.environ=environ
        self.db=db
        self.route=environ.get('PATH_INFO') or '/'
        self.mount=environ.get('SCRIPT_NAME','').rstrip('/')
        self.method=environ.get('REQUEST_METHOD','GET')
        self.query={k:v[-1] for k,v in parse_qs(environ.get('QUERY_STRING',''),max_num_fields=40).items()}
        self.data={}
        self.files={}
        self.setting=config(db)
        self.user=None
        self.session={}
        self.cookie=''
        self.token=''
        self.session_changed=False
        self.loaded=False

    def load(self):
        if self.loaded:
            return
        self.loaded=True
        incoming=SimpleCookie()
        try:
            incoming.load(self.environ.get('HTTP_COOKIE',''))
        except Exception:
            incoming=SimpleCookie()
        token=incoming['astha_sid'].value if 'astha_sid' in incoming else ''
        if re.fullmatch(r'[a-f0-9]{64}',token):
            found=one(self.db,'SELECT payload FROM sessions WHERE token=? AND touched>?',(token,int(time.time())-43200))
            if found:
                self.token=token
                self.session=json.loads(found['payload'])
        if not self.token:
            self.rotate()
        if self.session.get('user'):
            self.user=one(self.db,'SELECT id,username,name,role,registration FROM users WHERE id=? AND active=1',(self.session['user'],))

    def rotate(self,user=None):
        if self.token:
            self.db.execute('DELETE FROM sessions WHERE token=?',(self.token,))
        self.token=secrets.token_hex(32)
        self.session={'csrf':secrets.token_urlsafe(32)}
        if user:
            self.session['user']=user
        self.session_changed=True
        scope=self.mount or '/'
        secure='; Secure' if self.environ.get('wsgi.url_scheme')=='https' or os.environ.get('ASTHA_SECURE_COOKIE')=='1' else ''
        self.cookie=f'astha_sid={self.token}; Path={scope}; HttpOnly; SameSite=Lax'+secure

    def save(self):
        if self.session_changed:
            self.db.execute('INSERT INTO sessions VALUES(?,?,?) ON CONFLICT(token) DO UPDATE SET payload=excluded.payload,touched=excluded.touched',
               (self.token,json.dumps(self.session),int(time.time())))

    def flash(self, text, level='success'):
        self.session['flash']=[text,level]
        self.session_changed=True

    def consume_flash(self):
        if 'flash' not in self.session:
            return None
        self.session_changed=True
        return self.session.pop('flash')

    def url(self,path,**params):
        return self.mount+path+('?' + urlencode(params) if params else '')

    def parse(self):
        try:
            size=int(self.environ.get('CONTENT_LENGTH') or 0)
        except ValueError:
            raise Invalid('Invalid upload length.') from None
        if size<0 or size>25*1024*1024:
            raise Invalid('Upload limit is 25 MB.')
        body=self.environ['wsgi.input'].read(size)
        content_type=self.environ.get('CONTENT_TYPE','')
        if content_type.startswith('multipart/form-data'):
            message=BytesParser(policy=default).parsebytes(('Content-Type: '+content_type+'\r\n\r\n').encode()+body)
            for part in message.iter_parts():
                name=part.get_param('name',header='content-disposition')
                if not name:
                    continue
                if part.get_filename():
                    self.files[name]=part.get_payload(decode=True)
                else:
                    self.data[name]=part.get_content()
        else:
            self.data={k:v[-1] for k,v in parse_qs(body.decode('utf-8'),keep_blank_values=True,max_num_fields=250).items()}
        if not hmac.compare_digest(self.data.get('csrf',''),self.session['csrf']):
            raise Invalid('Form session expired. Refresh the page and try again.')

    def allow(self,key):
        return self.user and key in PERMISSIONS.get(self.user['role'],set())

def save_rx(raw):
    if not raw:
        return ('','')
    signatures=((b'%PDF-','application/pdf'),(b'\xff\xd8\xff','image/jpeg'),(b'\x89PNG\r\n\x1a\n','image/png'))
    mime=next((kind for prefix,kind in signatures if raw.startswith(prefix)),None)
    if not mime or len(raw)>8*1024*1024:
        raise Invalid('Prescription must be a PDF, JPG or PNG up to 8 MB.')
    directory=DATA/'prescriptions'
    directory.mkdir(mode=0o700,exist_ok=True)
    name=secrets.token_hex(32)
    fd=os.open(directory/name,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
    with os.fdopen(fd,'wb') as out:
        out.write(raw)
    return name,mime

def build_cart(data):
    cart={}
    for key,val in data.items():
        if re.fullmatch(r'qty_[1-9][0-9]{0,9}',key) and val not in ('','0'):
            cart[key[4:]]=integer(val,1,10000)
    return cart

def attempt(db,key,limit,window):
    record=one(db,'SELECT * FROM attempts WHERE key=?',(key,))
    started=int(time.time())
    if not record or record['started'] < started-window:
        db.execute('INSERT INTO attempts VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET count=excluded.count,started=excluded.started',(key,1,started))
        return True
    if record['count']>=limit:
        return False
    db.execute('UPDATE attempts SET count=count+1 WHERE key=?',(key,))
    return True

ACTIONS={
    'generic':'generics','product':'catalog','import_preview':'catalog','import_apply':'catalog','receive':'purchases','supplier':'suppliers',
    'supplier_payment':'reports','cash_close':'reports','stock_count':'inventory','supplier_return':'inventory','batch_hold':'inventory','transfer':'inventory','order_status':'orders','return':'orders',
    'staff':'staff','staff_toggle':'staff','settings':'settings','zone':'settings','zone_toggle':'settings','branch':'settings','ticket_close':'tickets'
}

def admin_action(r,key):
    d=r.data
    db=r.db
    user=r.user['id']
    if key=='generic':
        if r.user['role'] not in ('owner','pharmacist') or not r.user['registration']:
            raise Invalid('A registered pharmacist must verify generic reference fields.')
        gid=integer(d.get('id'))
        link=field(d,'source_url',300)
        if link and not link.startswith('https://'):
            raise Invalid('The source must use HTTPS.')
        clinical={k: field(d,k,10000) for k in CLINICAL if d.get(k)}
        if clinical.get('leaflet_url') and not clinical['leaflet_url'].startswith('https://'):
            raise Invalid('The leaflet must use HTTPS.')
        db.execute('UPDATE generics SET bangla=?, drug_class=?, ingredients=?, source_url=?, verified_on=?, clinical=? WHERE id=?',
          (field(d,'bangla'),field(d,'drug_class'),field(d,'ingredients',600),link,today(),json.dumps(clinical,ensure_ascii=False),gid))
        audit(db,user,'Generic reference verified',str(gid))
        return 'Generic reference saved.'
    if key=='product':
        pid=integer(d['id']) if d.get('id') else None
        p=product_data(d)
        if pid:
            old=one(db,'SELECT * FROM products WHERE id=?',(pid,))
            if not old:
                raise Invalid('Medicine not found.')
            if one(db,'SELECT 1 FROM batches WHERE product_id=? LIMIT 1',(pid,)) and any(old[k]!=p[k] for k in ('sku','sale_unit')):
                raise Invalid('Create a new SKU to change the base sale unit on a stocked item.')
        save_product(db,p,pid)
        audit(db,user,'Product saved',p['sku'])
        return 'Product saved.'
    if key=='import_preview':
        if r.user['role'] not in ('owner','manager','pharmacist'):
            raise Invalid('Import permission is required.')
        content=r.files.get('csv',b'')
        data=import_rows(workbook_to_csv(content) if content.startswith(b'PK\x03\x04') else content)
        for p in data:
            p.update(verified=0,online=0,verified_on='')
        token=secrets.token_hex(20)
        directory=DATA/'imports'
        directory.mkdir(mode=0o700,exist_ok=True)
        for old in directory.glob('*.json'):
            if old.stat().st_mtime<time.time()-1800:
                old.unlink(missing_ok=True)
        (directory/(token+'.json')).write_text(json.dumps(data,ensure_ascii=False))
        r.session['import']={'token':token,'count':len(data),'example':[p['sku']+' · '+p['brand'] for p in data[:8]]}
        r.session_changed=True
        return f'{len(data):,} rows validated. Review and apply to add new products.'
    if key=='import_apply':
        pending=r.session.get('import')
        if not pending:
            raise Invalid('Upload a CSV to preview an import.')
        path=DATA/'imports'/(pending['token']+'.json')
        if not path.is_file():
            raise Invalid('The preview expired. Upload your CSV again.')
        new=0
        existing=0
        for p in json.loads(path.read_text()):
            if one(db,'SELECT id FROM products WHERE sku=?',(p['sku'],)):
                existing+=1
            else:
                save_product(db,p)
                new+=1
        audit(db,user,'Catalog import',f'{new} new SKU(s), {existing} existing')
        r.session.pop('import',None)
        r.session_changed=True
        return f'Imported {new:,} new SKUs for verification. Kept {existing:,} existing SKUs.'
    if key=='supplier':
        db.execute('INSERT INTO suppliers(name,phone,address) VALUES(?,?,?)',
             (field(d,'name',100,True),field(d,'phone',40),field(d,'address',200)))
        return 'Supplier added.'
    if key=='receive':
        purchase=receive(db,d,user)
        audit(db,user,'Batch received',str(purchase))
        return 'Purchase batch received.'
    if key=='cash_close':
        branch=integer(d.get('branch'))
        day=date(d.get('date',''))
        if day>today() or not one(db,'SELECT 1 FROM branches WHERE id=?',(branch,)):
            raise Invalid('Choose a valid branch and date.')
        expected=one(db,"SELECT COALESCE(SUM(subtotal),0) total FROM orders WHERE channel='POS' AND status='Delivered' AND payment='Cash' AND branch_id=? AND SUBSTR(created,1,10)=?",(branch,day))['total']
        refunds=one(db,"SELECT COALESCE(SUM(r.amount),0) total FROM returns r JOIN lines l ON l.id=r.line_id JOIN orders o ON o.id=l.order_id WHERE o.channel='POS' AND o.payment='Cash' AND o.branch_id=? AND SUBSTR(r.created,1,10)=?",(branch,day))['total']
        counted=amount(d.get('counted',''))
        db.execute('INSERT INTO closings(branch_id,sale_date,expected,counted,note,closed_by,created) VALUES(?,?,?,?,?,?,?)',
          (branch,day,expected-refunds,counted,field(d,'note',250),user,now()))
        audit(db,user,'Cash closing',f'{branch} · {day}')
        return 'Cash closing saved.'
    if key=='stock_count':
        bid=integer(d.get('id'))
        b=one(db,'SELECT * FROM batches WHERE id=?',(bid,))
        count=integer(d.get('quantity'),0)
        reason=field(d,'reason',200,True)
        if not b or count<b['reserved']:
            raise Invalid('Physical stock cannot be lower than reserved stock.')
        db.execute('UPDATE batches SET qty=? WHERE id=?',(count,bid))
        movement(db,bid,count-b['qty'],'Physical stock count',reason)
        audit(db,user,'Stock count',b['lot'])
        return 'Physical stock count recorded.'
    if key=='supplier_return':
        bid=integer(d.get('id'))
        b=one(db,'SELECT * FROM batches WHERE id=?',(bid,))
        qty=integer(d.get('quantity'))
        if not b or not b['purchase_id'] or qty>b['qty']-b['reserved']:
            raise Invalid('Return quantity exceeds unreserved supplier stock.')
        reason=field(d,'reason',200,True)
        credit=amount(d.get('credit',''))
        if credit>qty*b['cost']:
            raise Invalid('Supplier credit cannot exceed original cost.')
        db.execute('UPDATE batches SET qty=qty-? WHERE id=?',(qty,bid))
        db.execute('INSERT INTO supplier_returns(batch_id,quantity,credit,reason,created) VALUES(?,?,?,?,?)',(bid,qty,credit,reason,now()))
        movement(db,bid,-qty,'Supplier return',reason)
        audit(db,user,'Supplier return',b['lot'])
        return 'Supplier return recorded.'
    if key=='supplier_payment':
        pid=integer(d.get('purchase'))
        cost=one(db,'SELECT COALESCE(SUM(received_qty*cost),0) n FROM batches WHERE purchase_id=?',(pid,))['n']
        paid=one(db,'SELECT COALESCE(SUM(amount),0) n FROM payments WHERE purchase_id=?',(pid,))['n']
        credit=one(db,'SELECT COALESCE(SUM(r.credit),0) n FROM supplier_returns r JOIN batches b ON b.id=r.batch_id WHERE b.purchase_id=?',(pid,))['n']
        value=amount(d.get('amount',''))
        if not value or value>cost-paid-credit:
            raise Invalid('Payment must be within the outstanding balance.')
        db.execute('INSERT INTO payments(purchase_id,amount,reference,created) VALUES(?,?,?,?)',(pid,value,field(d,'reference',100,True),now()))
        audit(db,user,'Supplier payment',str(pid))
        return 'Supplier payment recorded.'
    if key in ('batch_hold','transfer'):
        bid=integer(d.get('id'))
        batch=one(db,'SELECT * FROM batches WHERE id=?',(bid,))
        if not batch:
            raise Invalid('Batch not found.')
        if key=='batch_hold':
            target=integer(d.get('hold'),0,1)
            if not target and batch['expiry']<=today():
                raise Invalid('Expired batches stay on hold.')
            reason=field(d,'reason',180,True)
            db.execute('UPDATE batches SET hold=? WHERE id=?',(target,bid))
            audit(db,user,'Batch held' if target else 'Batch released',batch['lot']+' · '+reason)
            return 'Batch status updated.'
        branch=integer(d.get('branch'))
        qty=integer(d.get('quantity'))
        if branch==batch['branch_id'] or qty>batch['qty']-batch['reserved'] or batch['hold'] or batch['expiry']<=today() or not one(db,'SELECT id FROM branches WHERE id=? AND active=1',(branch,)):
            raise Invalid('Choose a different active branch and available sellable quantity.')
        db.execute('UPDATE batches SET qty=qty-? WHERE id=?',(qty,bid))
        dest=db.execute('INSERT INTO batches(product_id,branch_id,lot,expiry,manufactured,cost,qty) VALUES(?,?,?,?,?,?,?)',
            (batch['product_id'],branch,batch['lot'],batch['expiry'],batch['manufactured'],batch['cost'],qty)).lastrowid
        movement(db,bid,-qty,'Transfer out',str(dest))
        movement(db,dest,qty,'Transfer in',str(bid))
        audit(db,user,'Branch transfer',batch['lot']+' · '+str(qty))
        return 'Branch transfer recorded.'
    if key=='order_status':
        change_order(db,integer(d.get('id')),d.get('target'),d,r.user)
        return 'Order updated.'
    if key=='return':
        if r.user['role'] not in ('owner','manager','pharmacist'):
            raise Invalid('Return approval requires a manager or pharmacist.')
        return_item(db,integer(d.get('line')),integer(d.get('quantity')),field(d,'note',250,True),user)
        return 'Return recorded and moved to quarantine.'
    if key=='staff':
        role=d.get('role')
        if role not in PERMISSIONS or role=='owner':
            raise Invalid('Choose a staff role.')
        create_user(db,d,role)
        audit(db,user,'Staff account created',d['username'])
        return 'Staff account created.'
    if key=='staff_toggle':
        uid=integer(d.get('id'))
        db.execute("UPDATE users SET active=1-active WHERE id=? AND role<>'owner'",(uid,))
        audit(db,user,'Staff account status',str(uid))
        return 'Staff account updated.'
    if key=='settings':
        settings={k:field(d,k,600) for k in (*LIVE_KEYS,'store','mode','accent')}
        settings['store']=settings['store'] or 'Astha Pharmacy'
        settings['license_expiry']=date(settings['license_expiry'],True)
        if settings['mode'] not in ('draft','live','demo'):
            raise Invalid('Choose a valid store mode.')
        if settings['mode']=='demo' and not one(db,"SELECT 1 FROM products WHERE source='Demo'"):
            raise Invalid('Demo mode is only available for a demo installation.')
        if settings['mode']=='live' and mode(settings)!='live':
            raise Invalid('Complete all compliance fields with a current online licence.')
        if settings['pharmacist_photo'] and not settings['pharmacist_photo'].startswith('https://'):
            raise Invalid('Use an HTTPS image URL.')
        if settings['accent'] not in ('','forest','violet','ocean'):
            raise Invalid('Choose a workspace theme.')
        db.executemany('INSERT INTO settings VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value',settings.items())
        audit(db,user,'Store settings updated',settings['mode'])
        return 'Store settings saved.'
    if key=='branch':
        db.execute('INSERT INTO branches(name,address) VALUES(?,?)',(field(d,'name',110,True),field(d,'address',300,True)))
        return 'Branch added.'
    if key=='zone':
        db.execute('INSERT INTO zones(name,fee,eta,branch_id) VALUES(?,?,?,?)',
            (field(d,'name',100,True),amount(d.get('fee','')),field(d,'eta',100,True),integer(d.get('branch'))))
        return 'Delivery zone added.'
    if key=='zone_toggle':
        db.execute('UPDATE zones SET active=1-active WHERE id=?',(integer(d.get('id')),))
        return 'Delivery zone updated.'
    if key=='ticket_close':
        db.execute("UPDATE tickets SET resolution=?,status='Resolved' WHERE id=? AND status='Open'",
                   (field(d,'resolution',800,True),integer(d.get('id'))))
        return 'Complaint resolved.'
    raise Invalid('Unknown operation.')

def execute_post(r):
    r.parse()
    db=r.db
    key=r.data.get('action','')
    d=r.data
    if r.route=='/setup' and key=='setup':
        with write(db):
            if one(db,'SELECT id FROM users LIMIT 1'):
                raise Invalid('Setup is already complete.')
            token=os.environ.get('ASTHA_SETUP_KEY','')
            if not token or not hmac.compare_digest(token,d.get('setup_key','')):
                raise Invalid('Enter the installation key configured on the server.')
            uid=create_user(db,d,'owner')
            if d.get('demo')=='on':
                seed_demo(db,uid)
            r.rotate(uid)
        return '/admin'
    if r.route=='/login' and key=='login':
        name=field(d,'username',48,True).lower()
        ip=r.environ.get('REMOTE_ADDR','local')
        with write(db):
            allowed=attempt(db,'login:'+ip,12,900)
        found=one(db,'SELECT * FROM users WHERE username=? AND active=1',(name,))
        stored=found['password'] if found else '00'*16+'$'+'0'*128
        valid=allowed and password_valid(field(d,'password',128),stored)
        if not found or not valid:
            raise Invalid('Unable to sign in. Check your details or try again in 15 minutes.')
        r.rotate(found['id'])
        return '/admin'
    if key=='logout' and r.user:
        r.rotate()
        return '/login'
    if key in ('cart_add','cart_update') and r.route in ('/','/cart','/product'):
        if mode(r.setting)=='draft':
            raise Invalid('Online checkout is closed.')
        cart=r.session.get('cart',{}).copy()
        if key=='cart_add':
            pid=integer(d.get('id'))
            product=one(db,"SELECT * FROM products WHERE id=? AND online=1 AND verified=1 AND cold=0 AND classification IN ('otc','rx','general')",(pid,))
            if not product or (mode(r.setting)=='live' and product['source']=='Demo'):
                raise Invalid('This product is unavailable online.')
            if len(cart)>=100 and str(pid) not in cart:
                raise Invalid('A cart can contain at most 100 products.')
            cart[str(pid)]=integer(cart.get(str(pid),0)+integer(d.get('quantity',1)),1,10000)
        else:
            cart={pid:qty for pid,qty in build_cart(d).items() if pid in cart}
        r.session['cart']=cart
        r.session_changed=True
        r.flash('Cart updated.')
        return '/cart' if key=='cart_update' else '/'
    if r.route=='/cart' and key=='otp_send':
        if mode(r.setting)!='live' or not sms.configuration() or not r.session.get('cart'):
            raise Invalid('Mobile verification requires an active cart and SMS service.')
        phone=normalize_phone(d.get('verify_phone',''))
        ip=r.environ.get('REMOTE_ADDR','local')
        with write(db):
            ip_allowed=attempt(db,'sms-ip:'+ip,8,1800)
            phone_allowed=attempt(db,'sms-phone:'+phone,3,900)
        if not ip_allowed or not phone_allowed:
            raise Invalid('Code request limit reached. Try again later.')
        code=f'{secrets.randbelow(1000000):06d}'
        sms.send(phone,code)
        signature=hmac.new(r.token.encode(),(phone+code).encode(),hashlib.sha256).hexdigest()
        r.session['otp']={'phone':phone,'digest':signature,'expires':int(time.time())+300,'tries':0}
        r.session.pop('verified_mobile',None)
        r.session_changed=True
        r.flash('Verification code sent.')
        return '/cart'
    if r.route=='/cart' and key=='otp_confirm':
        otp=r.session.get('otp',{})
        code=field(d,'otp_code',6,True)
        if otp.get('expires',0)<time.time() or otp.get('tries',5)>=5:
            raise Invalid('Request a new verification code.')
        signature=hmac.new(r.token.encode(),(otp['phone']+code).encode(),hashlib.sha256).hexdigest()
        otp['tries']+=1
        r.session_changed=True
        if not hmac.compare_digest(otp['digest'],signature):
            raise Invalid('The verification code did not match.')
        r.session['verified_mobile']={'phone':otp['phone'],'expires':int(time.time())+1800}
        r.session.pop('otp',None)
        r.flash('Mobile number verified.')
        return '/cart'
    if key in ('checkout','pos') and r.route in ('/cart','/admin'):
        is_pos=key=='pos'
        if is_pos and (r.route!='/admin' or not r.allow('pos')):
            raise Invalid('Point of sale permission required.')
        if not is_pos and r.route!='/cart':
            raise Invalid('Open the cart to check out.')
        if not is_pos and mode(r.setting)=='live':
            mobile=r.session.get('verified_mobile',{})
            if not sms.configuration() or mobile.get('phone')!=normalize_phone(d.get('phone','')) or mobile.get('expires',0)<time.time():
                raise Invalid('Verify the mobile number before placing a live order.')
        if not is_pos:
            with write(db):
                if not attempt(db,'order:'+r.environ.get('REMOTE_ADDR','local'),20,3600):
                    raise Invalid('Order limit reached. Try again later.')
        submission=d.get('submission','')
        if not re.fullmatch(r'[a-f0-9]{32}',submission):
            raise Invalid('Refresh the sale form and try again.')
        scope=('POS:'+str(r.user['id'])) if is_pos else ('Cart:'+hashlib.sha256(r.token.encode()).hexdigest())
        file_info=save_rx(r.files.get('rx'))
        reused=False
        try:
            with write(db):
                expire_orders(db)
                previous=one(db,'SELECT o.id,o.code FROM submitted_sales s JOIN orders o ON o.id=s.order_id WHERE token=? AND scope=?',(submission,scope))
                if previous:
                    oid,code=previous['id'],previous['code']
                    reused=True
                else:
                    oid,code=place(db,build_cart(d) if is_pos else r.session.get('cart',{}),d,'POS' if is_pos else 'Online',file_info,r.user if is_pos else None,gateway_enabled=bool(gateway.configuration()))
                    db.execute('INSERT INTO submitted_sales VALUES(?,?,?)',(submission,scope,oid))
        except BaseException:
            if file_info[0]:
                (DATA/'prescriptions'/file_info[0]).unlink(missing_ok=True)
            raise
        if reused and file_info[0]:
            (DATA/'prescriptions'/file_info[0]).unlink(missing_ok=True)
        if is_pos:
            return '/admin/invoice?order='+str(oid)
        r.session.pop('cart',None)
        r.session['tracking']=oid
        r.session_changed=True
        r.flash('Order received. Keep your order number '+code+'.')
        return '/track?code='+code
    if r.route=='/track' and key=='pay':
        if not gateway.configuration() or mode(r.setting)!='live':
            raise Invalid('Hosted payment is unavailable.')
        oid=r.session.get('tracking')
        with write(db):
            order=one(db,"SELECT o.*, c.email FROM orders o JOIN checkout_contacts c ON c.order_id=o.id WHERE o.id=?",(oid,))
            if not order or order['status'] not in ('Confirmed','Packing') or order['payment']!='SSLCommerz' or order['paid']:
                raise Invalid('This order is not available for online payment.')
            payment=one(db,'SELECT * FROM online_payments WHERE order_id=?',(oid,))
            if payment and (datetime.now(TZ)-datetime.fromisoformat(payment['updated'])).total_seconds()<60:
                raise Invalid('Wait a minute before restarting a hosted payment.')
            db.execute("INSERT INTO online_payments(order_id,gateway_state,updated) VALUES(?,'Starting',?) ON CONFLICT(order_id) DO UPDATE SET gateway_state='Starting',updated=excluded.updated",(oid,now()))
        try:
            location,session_key=gateway.initiate(order)
        except Invalid:
            with write(db):
                db.execute("UPDATE online_payments SET gateway_state='Failed' WHERE order_id=? AND gateway_state='Starting'",(oid,))
            raise
        with write(db):
            db.execute("UPDATE online_payments SET gateway_state='Initiated',session_key=?,updated=? WHERE order_id=? AND gateway_state='Starting'",(session_key,now(),oid))
        return location
    if r.route=='/track' and key in ('track','complaint'):
        code=field(d,'code',40,True).upper()
        phone=normalize_phone(d.get('phone',''))
        with write(db):
            allowed=attempt(db,'track:'+r.environ.get('REMOTE_ADDR','local'),40,900)
            found=one(db,"SELECT id FROM orders WHERE code=? AND phone=? AND channel='Online'",(code,phone)) if allowed else None
            if found and key=='complaint':
                db.execute('INSERT INTO tickets(code,phone,body,created) VALUES(?,?,?,?)',(code,phone,field(d,'body',800,True),now()))
        if not found:
            raise Invalid('Order could not be found. Check the order number and mobile.')
        r.session['tracking']=found['id']
        r.session_changed=True
        if key=='complaint':
            r.flash('Complaint submitted.')
        return '/track?code='+code
    if r.route=='/admin' and key in ACTIONS and r.allow(ACTIONS[key]):
        if key=='product' and r.user['role'] not in ('owner','pharmacist','manager'):
            raise Invalid('Catalog edit permission is required.')
        if key=='product' and (d.get('verified') in ('on','1','true','yes')):
            if r.user['role'] not in ('owner','pharmacist') or not r.user['registration']:
                raise Invalid('A registered pharmacist account must verify products.')
        with write(db):
            feedback=admin_action(r,key)
        r.flash(feedback)
        extra=f"&order={integer(d.get('id'))}" if key=='order_status' else ''
        if key=='return' and d.get('invoice'):
            return '/admin/invoice?order='+str(integer(d['invoice']))
        return '/admin?page='+ACTIONS[key]+extra
    raise Invalid('The requested action is unavailable.')

def deliver(r,start,status,data,mime='text/html; charset=utf-8',extra=()):
    r.save()
    if isinstance(data,str):
        data=data.encode()
    headers=[('Content-Type',mime),('Content-Length',str(len(data))),('X-Content-Type-Options','nosniff'),
            ('Referrer-Policy','no-referrer'),('X-Frame-Options','DENY'),
            ('Content-Security-Policy',"default-src 'self'; img-src 'self' https:; style-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'")]
    if not r.route.startswith('/static/'):
        headers.append(('Cache-Control','no-store'))
    if r.cookie:
        headers.append(('Set-Cookie',r.cookie))
    start(status,headers+list(extra))
    return [data]

def redirect(r,start,dest):
    location=dest if dest.startswith('https://') else r.mount+dest
    return deliver(r,start,'303 See Other','',extra=(('Location',location),))


def payment_callback(r,start):
    cfg=gateway.configuration()
    if not cfg:
        return deliver(r,start,'404 Not Found','Payment unavailable.')
    try:
        length=integer(r.environ.get('CONTENT_LENGTH'),1,12000)
        data=parse_qs(r.environ['wsgi.input'].read(length).decode(),max_num_fields=120)
        claimed=data.get('tran_id',[''])[0]
        validation=data.get('val_id',[''])[0]
        if not re.fullmatch(r'APH-[A-F0-9]{16}',claimed):
            raise Invalid('Invalid payment order.')
        if not re.fullmatch(r'[A-Za-z0-9_-]{6,110}',validation):
            if r.route=='/payment/ipn':
                raise Invalid('Payment requires confirmation.')
            r.flash('Payment has not been confirmed. Check your order before retrying.','error')
            return redirect(r,start,'/track?code='+claimed)
        candidate=one(r.db,"SELECT o.* FROM orders o JOIN online_payments p ON p.order_id=o.id WHERE code=? AND payment='SSLCommerz'",(claimed,))
        if not candidate:
            raise Invalid('Payment order is unavailable.')
        reference,value,bank=gateway.validate(validation)
        if reference!=claimed or value!=candidate['subtotal']+candidate['delivery'] or not bank:
            raise Invalid('Payment details do not match.')
        with write(r.db):
            order=one(r.db,'SELECT * FROM orders WHERE id=?',(candidate['id'],))
            payment=one(r.db,'SELECT * FROM online_payments WHERE order_id=?',(order['id'],))
            if payment['gateway_state']=='Paid' and payment['bank_reference']==bank:
                pass
            elif payment['gateway_state'] in ('Starting','Initiated','Failed') and order['status'] in ('Confirmed','Packing'):
                r.db.execute("UPDATE online_payments SET gateway_state='Paid',bank_reference=?,updated=? WHERE order_id=?",(bank,now(),order['id']))
                r.db.execute('UPDATE orders SET paid=1 WHERE id=?',(order['id'],))
                audit(r.db,None,'Online payment confirmed',claimed)
            else:
                raise Invalid('Payment requires manual reconciliation.')
        if r.route=='/payment/ipn':
            return deliver(r,start,'200 OK','Payment confirmed.','text/plain; charset=utf-8')
        r.flash('Payment confirmed. Track the order with your mobile number.')
        return redirect(r,start,'/track?code='+claimed)
    except (Invalid,ValueError,sqlite3.IntegrityError,UnicodeError):
        return deliver(r,start,'400 Bad Request','Payment requires confirmation.','text/plain; charset=utf-8')

def application(environ,start):
    with closing(connect()) as db:
        try:
            r=Request(environ,db)
        except (ValueError,UnicodeError):
            start('400 Bad Request',[('Content-Type','text/plain')])
            return [b'Invalid query.']
        try:
            if r.route in ('/static/style.css','/static/app.js','/static/store.webp'):
                path=ROOT/r.route.lstrip('/')
                if path.is_file():
                    mime=mimetypes.guess_type(path)[0]
                    return deliver(r,start,'200 OK',path.read_bytes(),mime)
            r.load()
            installed=one(db,'SELECT id FROM users LIMIT 1')
            if not installed and r.route!='/setup':
                return redirect(r,start,'/setup')
            if installed and r.route=='/setup':
                return redirect(r,start,'/admin')
            if r.route.startswith('/admin') and not r.user:
                return redirect(r,start,'/login')
            if r.route in ('/payment/return','/payment/ipn') and r.method=='POST':
                return payment_callback(r,start)
            if r.method=='POST':
                return redirect(r,start,execute_post(r))
            if r.method not in ('GET','HEAD'):
                return deliver(r,start,'405 Method Not Allowed','Method not allowed.')
            if r.route=='/setup':
                return deliver(r,start,'200 OK',render_setup(r))
            if r.route=='/login':
                return redirect(r,start,'/admin') if r.user else deliver(r,start,'200 OK',render_login(r))
            if r.route=='/admin':
                page=r.query.get('page','dashboard')
                if page not in {name for group in NAV.values() for name in group} or not r.allow(page):
                    return deliver(r,start,'403 Forbidden',render_error(r,'This workspace requires permission.'))
                return deliver(r,start,'200 OK',render_admin(r,page,NAV,PERMISSIONS))
            if r.route=='/admin/lookup' and r.allow('pos'):
                key=r.query.get('q','').strip()[:160]
                branch=integer(r.query.get('branch','1'))
                clause,args=search_sql(key)
                entries=rows(db,f'''SELECT p.*, COALESCE(SUM(CASE WHEN b.hold=0 AND b.expiry>? THEN b.qty-b.reserved ELSE 0 END),0) AS available
                    FROM products p LEFT JOIN batches b ON b.product_id=p.id AND b.branch_id=?
                    WHERE ({clause}) AND p.verified=1 AND p.classification NOT IN ('blocked','pending')
                    GROUP BY p.id ORDER BY (p.barcode=? OR p.sku=?) DESC,p.brand LIMIT 25''',(today(),branch,*args,key,key))
                response=[{'id':p['id'],'label':product_label(p),'sku':p['sku'],'barcode':p['barcode'],'stock':p['available'],
                           'unit':p['sale_unit'],'units':p['pack_units'],'price':p['price'],'classification':CLASSES[p['classification']]} for p in entries]
                return deliver(r,start,'200 OK',json.dumps(response,ensure_ascii=False),'application/json; charset=utf-8')
            if r.route=='/admin/rx' and r.allow('rx'):
                order=one(db,'SELECT code,rx_file,rx_mime FROM orders WHERE id=?',(integer(r.query.get('order')),))
                if order and re.fullmatch('[0-9a-f]{64}',order['rx_file']):
                    path=DATA/'prescriptions'/order['rx_file']
                    if path.is_file():
                        with write(db):
                            audit(db,r.user['id'],'Prescription downloaded',order['code'])
                        ext={'application/pdf':'pdf','image/jpeg':'jpg','image/png':'png'}[order['rx_mime']]
                        return deliver(r,start,'200 OK',path.read_bytes(),order['rx_mime'],(('Content-Disposition',f'attachment; filename="prescription.{ext}"'),))
            if r.route=='/admin/invoice' and r.allow('invoice'):
                oid=integer(r.query.get('order'))
                order=one(db,'''SELECT o.*,b.name branch,b.address branch_address,u.name pharmacist_name,u.registration pharmacist_reg
                    FROM orders o JOIN branches b ON b.id=o.branch_id LEFT JOIN users u ON u.id=o.dispensed_by WHERE o.id=?''',(oid,))
                if order and (r.user['role']!='cashier' or order['operator_id']==r.user['id']):
                    return deliver(r,start,'200 OK',render_invoice(r,order))
            if r.route=='/admin/template' and r.allow('catalog'):
                cols=FIELDS+list(CLINICAL)
                return deliver(r,start,'200 OK',','.join(cols)+'\n','text/csv; charset=utf-8',(('Content-Disposition','attachment; filename="Astha_Catalog_Template.csv"'),))
            if r.route in ('/','/cart','/track','/product','/policy'):
                return deliver(r,start,'200 OK',render_store(r))
            return deliver(r,start,'404 Not Found',render_error(r,'This page is unavailable.'))
        except (Invalid,sqlite3.IntegrityError,UnicodeError) as error:
            message=str(error) if isinstance(error,Invalid) else 'An identifier already exists or the selected record is invalid.'
            if r.method=='POST':
                r.flash(message,'error')
                path=r.route if r.route in ('/setup','/login','/admin','/cart','/track','/') else '/'
                query=''
                if path=='/track' and r.session.get('tracking'):
                    saved=one(r.db,'SELECT code FROM orders WHERE id=?',(r.session['tracking'],))
                    if saved:
                        query='?code='+saved['code']
                if path=='/admin':
                    page=ACTIONS.get(r.data.get('action'), 'pos')
                    query='?page='+page
                    if page=='orders' and re.fullmatch(r'[1-9][0-9]{0,9}',r.data.get('id','')):
                        query+='&order='+r.data['id']
                return redirect(r,start,path+query)
            return deliver(r,start,'400 Bad Request',render_error(r,message))
        except Exception:
            logging.exception('Astha request failed')
            return deliver(r,start,'500 Internal Server Error',render_error(r,'The request could not be completed. Please try again.'))

initialize()
