"""Transactional customer CSV import with area matching; never runs Selenium."""
import argparse
import csv
from db import audit, connect, init, one
from engine import phone

def import_csv(db,path):
    count=0
    with open(path,encoding='utf-8-sig',newline='') as stream:
        reader=csv.DictReader(stream)
        if not {'name','phone','area'}<=set(reader.fieldnames or []):
            raise ValueError('CSV headers must include name,phone,area; optional shop,address,landmark,alternate_phone,notes')
        for line,row in enumerate(reader,2):
            name=row['name'].strip()
            if not name: raise ValueError(f'Line {line}: missing name')
            sender=phone(row['phone'])
            area=one(db,'SELECT id FROM areas WHERE business_id=1 AND name=? COLLATE NOCASE',(row['area'].strip(),))
            if not area: raise ValueError(f'Line {line}: unknown area {row["area"]}; configure it before importing')
            alternate=phone(row['alternate_phone']) if row.get('alternate_phone','').strip() else ''
            db.execute('INSERT INTO customers(business_id,name,phone,area_id,shop,address,landmark,alternate_phone,notes) VALUES(1,?,?,?,?,?,?,?,?) ON CONFLICT(business_id,phone) DO UPDATE SET name=excluded.name,area_id=excluded.area_id,shop=excluded.shop,address=excluded.address,landmark=excluded.landmark,alternate_phone=excluded.alternate_phone,notes=excluded.notes',(name,sender,area['id'],row.get('shop',''),row.get('address',''),row.get('landmark',''),alternate,row.get('notes','')))
            count+=1
    audit(db,'Customer CSV Imported',detail={'rows':count},actor='import-cli')
    return count

if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('csv_path');args=parser.parse_args()
    init()
    with connect() as db: count=import_csv(db,args.csv_path)
    print(f'Imported {count} customers. Any validation error rolls back the whole import.')
