import csv
import io
import json
import os
import secrets
import sqlite3
import unicodedata
from contextlib import contextmanager
from datetime import datetime, timedelta
from decimal import Decimal, InvalidOperation
from pathlib import Path
from zoneinfo import ZoneInfo

ROOT = Path(__file__).resolve().parent
DATA = Path(os.environ.get('ASTHA_DATA_DIR', str(Path.home() / '.astha-pharmacy'))).expanduser().resolve()
TZ = ZoneInfo('Asia/Dhaka')
CLASSES = {'otc': 'OTC', 'rx': 'Prescription', 'blocked': 'Blocked', 'pending': 'Pending verification', 'general': 'Healthcare'}
CATEGORIES = ('Medicine', 'Medical Devices', 'Baby Care', 'Personal Care', 'Health Essentials')
CLINICAL = ('indications', 'pharmacology', 'dosage', 'contraindications', 'side_effects', 'interactions', 'pregnancy_lactation', 'precautions', 'overdose', 'storage', 'leaflet_url')
FIELDS = 'sku brand brand_bn generic generic_bn maker strength form release category pack pack_units sale_unit barcode dar mrp price classification verified online cold min_stock source source_url image_url'.split()
PENDING = ('Review', 'Confirmed', 'Packing')
TERMINAL = ('Delivered', 'Cancelled', 'Rejected', 'Expired')
LIVE_KEYS = ('license', 'retail_license', 'license_expiry', 'address', 'phone', 'owner', 'pharmacist', 'registration', 'pharmacist_photo', 'hours', 'logistics', 'return_policy')

class Invalid(ValueError):
    pass

def now():
    return datetime.now(TZ).isoformat(timespec='seconds')

def today():
    return datetime.now(TZ).date().isoformat()

def money(value):
    return f'৳{(value or 0) / 100:,.2f}'

def amount(value):
    try:
        n = Decimal(str(value))
        if n.is_finite() and 0 <= n <= 10000000 and n == n.quantize(Decimal('.01')):
            return int(n * 100)
    except InvalidOperation:
        pass
    raise Invalid('Enter a valid amount in BDT with up to two decimal places.')

def integer(value, low=1, high=1000000):
    try:
        n = int(value)
        if low <= n <= high:
            return n
    except (TypeError, ValueError):
        pass
    raise Invalid(f'Enter a whole number from {low} to {high:,}.')

def field(data, key, maxlen=120, required=False):
    value = str(data.get(key, '') or '').strip()
    if (required and not value) or len(value) > maxlen:
        raise Invalid(f'Check {key.replace("_", " ")} (maximum {maxlen} characters).')
    return value

def date(value, optional=False):
    if optional and not value:
        return ''
    try:
        return datetime.strptime(value, '%Y-%m-%d').date().isoformat()
    except ValueError:
        raise Invalid('Enter valid dates.') from None

def connect():
    DATA.mkdir(mode=0o700, parents=True, exist_ok=True)
    connection = sqlite3.connect(DATA / 'pharmacy.sqlite3', timeout=12, isolation_level=None)
    connection.row_factory = sqlite3.Row
    connection.execute('PRAGMA foreign_keys=ON')
    connection.execute('PRAGMA busy_timeout=12000')
    return connection

def initialize():
    with connect() as db:
        db.execute('PRAGMA journal_mode=WAL')
        db.executescript((ROOT / 'schema.sql').read_text())
        db.execute("INSERT OR IGNORE INTO branches(id,name,address) VALUES(1,'Main Branch','Dhaka')")
        db.execute("INSERT OR IGNORE INTO settings VALUES('store','Astha Pharmacy')")
        db.execute("INSERT OR IGNORE INTO settings VALUES('mode','draft')")
        missing=rows(db,"SELECT p.* FROM products p WHERE category='Medicine' AND generic<>'' AND NOT EXISTS (SELECT 1 FROM product_generics WHERE product_id=p.id)")
        if missing:
            with write(db):
                for p in missing:
                    link_generic(db,p['id'],p['generic'],p['generic_bn'])

@contextmanager
def write(db):
    db.execute('BEGIN IMMEDIATE')
    try:
        yield
    except BaseException:
        db.rollback()
        raise
    else:
        db.commit()

def one(db, sql, params=()):
    return db.execute(sql, params).fetchone()

def rows(db, sql, params=()):
    return db.execute(sql, params).fetchall()

def config(db):
    return {r['key']: r['value'] for r in rows(db, 'SELECT * FROM settings')}

def mode(settings):
    selected = settings.get('mode')
    if selected == 'demo':
        return 'demo'
    if selected == 'live' and all(settings.get(k) for k in LIVE_KEYS) and settings.get('license_expiry','') >= today():
        return 'live'
    return 'draft'

def audit(db, actor, action, detail):
    db.execute('INSERT INTO audit(user_id, action, detail, created) VALUES(?,?,?,?)', (actor, action, detail, now()))

def stock(db, branch=None):
    return rows(db, """SELECT p.*, COALESCE(SUM(CASE WHEN b.expiry>? AND b.hold=0 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 (? IS NULL OR b.branch_id=?)
       GROUP BY p.id ORDER BY p.brand COLLATE NOCASE,p.id""", (today(),branch,branch))

def search_sql(query):
    # Escape SQL wildcards so a literal SKU or barcode remains searchable.
    pattern = '%' + query.replace('!', '!!').replace('%','!%').replace('_','!_') + '%'
    columns = ('brand','brand_bn','generic','generic_bn','maker','sku','barcode')
    return ' OR '.join(f'p.{col} LIKE ? ESCAPE \'!\'' for col in columns), (pattern,) * len(columns)

def search(db, query, public=False, category='', page=1, size=30):
    clause, args = search_sql(query)
    filters = [f'({clause})']
    args = list(args)
    if public:
        filters.append("p.online=1 AND p.verified=1 AND p.cold=0 AND p.classification IN ('otc','rx','general')")
    if category:
        filters.append('p.category=?')
        args.append(category)
    filters = ' AND '.join(filters)
    count = one(db, 'SELECT COUNT(*) n FROM products p WHERE ' + filters, args)['n']
    items = rows(db, f"""SELECT p.*, COALESCE(SUM(CASE WHEN b.expiry>? AND b.hold=0 AND br.active=1 THEN b.qty-b.reserved ELSE 0 END),0) AS available
         FROM products p LEFT JOIN batches b ON b.product_id=p.id LEFT JOIN branches br ON br.id=b.branch_id
         WHERE {filters} GROUP BY p.id ORDER BY p.brand COLLATE NOCASE,p.id LIMIT ? OFFSET ?""",
         [today(),*args,size,(page-1)*size])
    return items,count

def product_data(data):
    result = {k: field(data,k,200) for k in FIELDS}
    for k in ('sku','brand','category','classification','sale_unit'):
        result[k] = field(data,k,120,True)
    if result['classification'] not in CLASSES or result['category'] not in CATEGORIES:
        raise Invalid('Choose a valid category and sale class.')
    if result['category'] == 'Medicine' and not result['generic']:
        raise Invalid('A generic name is required for medicines.')
    if result['category'] == 'Medicine' and result['classification'] == 'general':
        raise Invalid('Medicine requires a medicine sale class.')
    for k in ('mrp','price'):
        result[k] = amount(data.get(k,''))
    if result['price'] > result['mrp']:
        raise Invalid('Selling price must be within MRP.')
    for k in ('online','verified','cold'):
        result[k] = int(str(data.get(k,'' )).lower() in ('1','on','true','yes'))
    if result['category'] == 'Medicine' and result['verified'] and (
        not result['dar'] or not result['source'] or result['classification'] == 'pending'
    ):
        raise Invalid('Verified medicines require DAR/MA, a source and a confirmed sale class.')
    for k in ('pack_units','min_stock'):
        result[k] = integer(data.get(k) or (1 if k=='pack_units' else 5), int(k=='pack_units'), 100000)
    for k in ('source_url','image_url'):
        if result[k] and not result[k].startswith('https://'):
            raise Invalid('Source and image links must use HTTPS.')
    clinical = {k: field(data,k,10000) for k in CLINICAL if data.get(k)}
    if clinical.get('leaflet_url') and not clinical['leaflet_url'].startswith('https://'):
        raise Invalid('Leaflet links must use HTTPS.')
    result['clinical'] = json.dumps(clinical,ensure_ascii=False)
    result['verified_on'] = today() if result['verified'] else ''
    return result

def generic_key(label):
    return ' '.join(unicodedata.normalize('NFKC',label).casefold().split())

def link_generic(db,pid,label,bangla=''):
    if not label:
        db.execute('DELETE FROM product_generics WHERE product_id=?',(pid,))
        return
    key=generic_key(label)
    db.execute("INSERT INTO generics(lookup_key,name,bangla) VALUES(?,?,?) ON CONFLICT(lookup_key) DO NOTHING",(key,label,bangla))
    gid=one(db,'SELECT id FROM generics WHERE lookup_key=?',(key,))['id']
    db.execute('INSERT INTO product_generics VALUES(?,?) ON CONFLICT(product_id) DO UPDATE SET generic_id=excluded.generic_id',(pid,gid))

def save_product(db, p, pid=None):
    keys = list(p)
    if pid is not None:
        db.execute('UPDATE products SET '+','.join(f'{k}=?' for k in keys)+' WHERE id=?', [*p.values(),pid])
    else:
        pid=db.execute('INSERT INTO products ('+','.join(keys)+') VALUES('+','.join('?' for _ in keys)+')', tuple(p.values())).lastrowid
    if p['category']=='Medicine':
        link_generic(db,pid,p['generic'],p['generic_bn'])
    else:
        link_generic(db,pid,'')

def import_rows(file):
    try:
        reader = csv.DictReader(io.StringIO(file.decode('utf-8-sig')))
        if (not reader.fieldnames or len(reader.fieldnames) != len(set(reader.fieldnames))
            or not set(('sku','brand','category','sale_unit','classification','mrp','price')) <= set(reader.fieldnames)):
            raise Invalid('Use the Astha CSV template with its header.')
        data = []
        seen = set()
        for index,row in enumerate(reader,2):
            if index > 60002:
                raise Invalid('Split files into at most 60,000 rows.')
            if not any(row.values()):
                continue
            try:
                if None in row:
                    raise Invalid('Unexpected extra columns.')
                p = product_data(row)
                sku = p['sku']
                if sku in seen:
                    raise Invalid(f'Duplicate SKU {sku}.')
                seen.add(sku)
                data.append(p)
            except Invalid as error:
                raise Invalid(f'CSV row {index} · {error}') from error
        if not data:
            raise Invalid('The file has no data rows.')
        return data
    except (UnicodeError,csv.Error):
        raise Invalid('Save the file as UTF-8 CSV and try again.') from None

def receive(db, data, actor):
    branch = integer(data.get('branch'))
    supplier = integer(data.get('supplier'))
    reference = field(data,'reference',100,True)
    if not one(db,'SELECT id FROM branches WHERE id=? AND active=1',(branch,)) or not one(db,'SELECT id FROM suppliers WHERE id=?',(supplier,)):
        raise Invalid('Choose an active branch and supplier.')
    expiry = date(data.get('expiry',''))
    made = date(data.get('manufactured',''),True)
    product = integer(data.get('product'))
    p = one(db,'SELECT * FROM products WHERE id=?',(product,))
    if not p:
        raise Invalid('Choose a product.')
    if expiry <= today() or (made and (made > today() or made >= expiry)):
        raise Invalid('Check the manufacturing and expiry dates.')
    purchase = one(db,'SELECT id FROM purchases WHERE supplier_id=? AND branch_id=? AND reference=?',(supplier,branch,reference))
    purchase_id = purchase['id'] if purchase else db.execute(
        'INSERT INTO purchases(supplier_id,branch_id,reference,created,user_id) VALUES(?,?,?,?,?)',
        (supplier,branch,reference,now(),actor)).lastrowid
    lot = field(data,'lot',80,True)
    shelf = field(data,'shelf',80)
    qty = integer(data.get('quantity'))
    cost = amount(data.get('cost'))
    if one(db,'SELECT id FROM batches WHERE purchase_id=? AND product_id=? AND lot=?',(purchase_id,product,lot)):
        raise Invalid('This product and lot already exist on the supplier invoice.')
    b = db.execute("""INSERT INTO batches(product_id,branch_id,purchase_id,lot,expiry,manufactured,shelf,qty,cost,received_qty)
        VALUES(?,?,?,?,?,?,?,?,?,?)""", (product,branch,purchase_id,lot,expiry,made,shelf,qty,cost,qty)).lastrowid
    movement(db,b,qty,'Purchase receipt',str(purchase_id))
    return purchase_id

def movement(db,batch,qty,reason,ref):
    db.execute('INSERT INTO movements(batch_id,delta,reason,ref,created) VALUES(?,?,?,?,?)',(batch,qty,reason,ref,now()))

def order_code():
    return 'APH-' + secrets.token_hex(8).upper()

def place(db, cart, data, channel, file_info=('', ''), user=None, gateway_enabled=False):
    if not cart or len(cart)>100:
        raise Invalid('Add up to 100 product lines.')
    online = channel == 'Online'
    settings = config(db)
    sales_mode = mode(settings)
    if online and sales_mode == 'draft':
        raise Invalid('Online checkout is closed.')
    if online:
        zone_id = integer(data.get('zone'))
        zone = one(db,'SELECT z.* FROM zones z JOIN branches b ON b.id=z.branch_id WHERE z.id=? AND z.active=1 AND b.active=1',(zone_id,))
        if not zone:
            raise Invalid('This delivery zone is unavailable.')
        branch = zone['branch_id']
        customer = field(data,'customer',100,True)
        phone = normalize_phone(data.get('phone',''))
        address = field(data,'address',360,True)
        if payment_email := data.get('email',''):
            if len(payment_email)>120 or '@' not in payment_email:
                raise Invalid('Enter a valid email address.')
        if data.get('customer_role') not in ('self','guardian'):
            raise Invalid('Confirm that you are the patient or their legal guardian.')
    else:
        zone = {'name':'','fee':0,'eta':''}
        branch = integer(data.get('branch'))
        if not one(db,'SELECT id FROM branches WHERE id=? AND active=1',(branch,)):
            raise Invalid('Choose an active branch.')
        customer = field(data,'customer',100) or 'Walk-in'
        phone = ''
        address = ''
    payment = field(data,'payment',20,True)
    if payment not in ((('COD','SSLCommerz') if gateway_enabled and sales_mode=='live' else ('COD',)) if online else ('Cash','bKash','Nagad','Card')):
        raise Invalid('Choose an available payment method.')
    allocations = []
    rx = False
    dispensing = None
    for pid,qty in cart.items():
        qty = integer(qty,1,10000)
        p = one(db,'SELECT * FROM products WHERE id=?',(integer(pid),))
        if not p or p['classification'] == 'pending' or not p['verified']:
            raise Invalid('One item needs catalog verification.')
        eligible = p['online'] and not p['cold'] and p['classification'] in ('otc','rx','general')
        if (online and not eligible) or (not online and p['classification']=='blocked'):
            raise Invalid('This sale channel is unavailable for an item.')
        if sales_mode == 'live' and p['source'] == 'Demo':
            raise Invalid('Demo items are restricted to the pilot.')
        rx = rx or p['classification'] == 'rx'
        remaining = qty
        for b in rows(db,'''SELECT * FROM batches WHERE product_id=? AND branch_id=? AND hold=0 AND expiry>? AND qty>reserved
                ORDER BY expiry,id''',(pid,branch,today())):
            take = min(remaining,b['qty']-b['reserved'])
            allocations.append((p,b,take))
            remaining -= take
            if not remaining:
                break
        if remaining:
            raise Invalid(f"Insufficient sellable stock at this branch for {p['brand']} {p['strength']}.")
    if rx and not file_info[0]:
        raise Invalid('Attach a prescription image or PDF.')
    if rx and not online:
        if not user or user['role'] not in ('owner','pharmacist') or not user['registration'] or data.get('rx_checked')!='on':
            raise Invalid('A registered pharmacist must verify this prescription before POS dispensing.')
        dispensing = user['id']
    status = 'Review' if online and rx else ('Confirmed' if online else 'Delivered')
    if not online and user['role'] in ('owner','pharmacist') and user['registration']:
        dispensing = user['id']
    subtotal=sum(p['price']*take for p,_,take in allocations)
    code=order_code()
    stamp=now()
    oid=db.execute("""INSERT INTO orders(code,channel,status,branch_id,customer,phone,address,zone,payment,subtotal,delivery,created,updated,
        rx_file,rx_mime,operator_id,reviewed_by,dispensed_by,reviewed_at,eta,paid)
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
        (code,channel,status,branch,customer,phone,address,zone['name'],payment,subtotal,zone['fee'],stamp,stamp,
         *file_info,user['id'] if user else None,dispensing if rx else None,dispensing,stamp if rx and not online else '',zone['eta'],int(not online))).lastrowid
    if online and payment=='SSLCommerz':
        if not data.get('email',''):
            raise Invalid('Email is required for hosted online payment.')
        db.execute('INSERT INTO checkout_contacts VALUES(?,?)',(oid,data['email'].strip()))
    for p,b,take in allocations:
        name=' '.join(s for s in (p['brand'],p['strength'],p['form']) if s)
        db.execute("""INSERT INTO lines(order_id,batch_id,product_id,name,maker,dar,lot,expiry,manufactured,sale_unit,qty,price,cost)
             VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",(oid,b['id'],p['id'],name,p['maker'],p['dar'],b['lot'],b['expiry'],b['manufactured'],p['sale_unit'],take,p['price'],b['cost']))
        if online:
            db.execute('UPDATE batches SET reserved=reserved+? WHERE id=?',(take,b['id']))
        else:
            db.execute('UPDATE batches SET qty=qty-? WHERE id=?',(take,b['id']))
            movement(db,b['id'],-take,'POS sale',code)
    audit(db,user['id'] if user else None,'Order created',f'{code} · {status}')
    return oid,code

def normalize_phone(value):
    value = str(value).strip().replace(' ','').replace('-','')
    if value.startswith('+880'):
        value = '0' + value[4:]
    if len(value)!=11 or not value.startswith('01') or not value.isascii() or not value.isdecimal():
        raise Invalid('Enter a Bangladeshi mobile number beginning 01.')
    return value

def cancel_order(db, order, state, note=''):
    if order['status'] not in PENDING:
        raise Invalid('Only an unshipped order can release its reservation.')
    for line in rows(db,'SELECT batch_id,qty FROM lines WHERE order_id=?',(order['id'],)):
        db.execute('UPDATE batches SET reserved=reserved-? WHERE id=?',(line['qty'],line['batch_id']))
    db.execute('UPDATE orders SET status=?,review_note=?,updated=? WHERE id=?',(state,note,now(),order['id']))

def expire_orders(db):
    cutoff=(datetime.now(TZ)-timedelta(hours=24)).isoformat(timespec='seconds')
    for order in rows(db,"SELECT * FROM orders WHERE status='Review' AND created<?",(cutoff,)):
        cancel_order(db,order,'Expired','Prescription review window expired.')
        audit(db,None,'Reservation expired',order['code'])

def change_order(db, oid, target, data, user):
    order=one(db,'SELECT * FROM orders WHERE id=?',(oid,))
    if not order or order['channel']!='Online':
        raise Invalid('Choose a valid online order.')
    previous=order['status']
    transitions={'Review':('Confirmed','Rejected','Cancelled'),'Confirmed':('Packing','Cancelled'),
                 'Packing':('Dispatched','Cancelled'),'Dispatched':('Delivered',)}
    if target not in transitions.get(previous,()):
        raise Invalid('This order has changed. Refresh and try again.')
    pharmacist=user['role'] in ('owner','pharmacist') and bool(user['registration'])
    note=field(data,'note',500)
    if previous=='Review':
        if target in ('Confirmed','Rejected') and not pharmacist:
            raise Invalid('A registered pharmacist must review this order.')
        if target=='Confirmed' and (data.get('checked')!='on' or not order['rx_file']):
            raise Invalid('Confirm that prescription and supplied items were checked.')
        if target=='Rejected' and not note:
            raise Invalid('Enter the reason for rejection.')
    if target in ('Cancelled','Rejected'):
        if order['payment']=='SSLCommerz' and (order['paid'] or one(db,"SELECT 1 FROM online_payments WHERE order_id=? AND gateway_state IN ('Starting','Initiated')",(oid,))):
            if not data.get('checked_refund')=='on' or not note:
                raise Invalid('Reconcile the gateway transaction and record its refund or void reference before cancelling.')
            db.execute("UPDATE online_payments SET gateway_state='Reconciled',updated=? WHERE order_id=?",(now(),oid))
        cancel_order(db,order,target,note)
    elif target=='Dispatched':
        if order['payment']=='SSLCommerz' and not order['paid']:
            raise Invalid('Online payment must be confirmed before dispatch.')
        if mode(config(db))=='draft':
            raise Invalid('Open sales mode and confirm licensing before dispatch.')
        tracking=field(data,'tracking',100)
        if not pharmacist:
            raise Invalid('A registered pharmacist must record dispatch.')
        lines=rows(db,'SELECT l.*, b.hold, p.verified, p.classification, p.online, p.cold, p.source FROM lines l JOIN batches b ON b.id=l.batch_id JOIN products p ON p.id=l.product_id WHERE order_id=?',(oid,))
        for line in lines:
            if (line['hold'] or line['expiry']<=today() or not line['verified'] or not line['online'] or line['cold']
                or line['classification'] not in ('general','otc','rx') or (line['classification']=='rx' and not order['reviewed_by'])
                or (mode(config(db))=='live' and line['source']=='Demo')):
                raise Invalid('A line is no longer eligible to dispatch. Cancel the order and confirm stock before reordering.')
            db.execute('UPDATE batches SET reserved=reserved-?,qty=qty-? WHERE id=?',(line['qty'],line['qty'],line['batch_id']))
            movement(db,line['batch_id'],-line['qty'],'Online dispatch',order['code'])
        db.execute('UPDATE orders SET status=?,tracking=?,dispensed_by=?,updated=? WHERE id=?',(target,tracking,user['id'],now(),oid))
    elif previous=='Review':
        db.execute('UPDATE orders SET status=?,review_note=?,reviewed_by=?,reviewed_at=?,updated=? WHERE id=?',(target,note,user['id'],now(),now(),oid))
    else:
        db.execute('UPDATE orders SET status=?,paid=?,updated=? WHERE id=?',(target,int(order['paid'] or target=='Delivered'),now(),oid))
    audit(db,user['id'],'Order status',f"{order['code']} · {previous} → {target}")

def return_item(db,lid,quantity,note,user):
    line=one(db,'SELECT l.*,o.status,o.code FROM lines l JOIN orders o ON o.id=l.order_id WHERE l.id=?',(lid,))
    if not line or line['status']!='Delivered' or quantity>line['qty']-line['returned']:
        raise Invalid('The return quantity exceeds the delivered balance.')
    db.execute('UPDATE lines SET returned=returned+? WHERE id=?',(quantity,lid))
    db.execute('INSERT INTO returns(line_id,qty,amount,reason,created) VALUES(?,?,?,?,?)',(lid,quantity,quantity*line['price'],note,now()))
    b=one(db,'SELECT * FROM batches WHERE id=?',(line['batch_id'],))
    new_id=db.execute("""INSERT INTO batches(product_id,branch_id,lot,expiry,manufactured,shelf,cost,qty,hold)
                VALUES(?,?,?,?,?,?,?,?,1)""",(b['product_id'],b['branch_id'],b['lot'],b['expiry'],b['manufactured'],'Returns quarantine',b['cost'],quantity)).lastrowid
    movement(db,new_id,quantity,'Customer return',line['code'])
    audit(db,user,'Return recorded',f"{line['code']} · {quantity} units")
