"""Regression coverage for the dealership photo editor, inventory, accounting and article workflows."""
import json
import sqlite3
import uuid


def run(req, owner, writer, accountant, database, root, bridge, mark):
    def post(path, data, actor=owner, status=200):
        return req('/api/staff/' + path, 'POST', data, actor, status=status)

    def listing(stock):
        response = req('/api/staff/inventory', c=owner)
        return next(row for row in response['rows'] + response['trash'] if row['stock'] == stock)

    def photo():
        raw = (root / 'public/photos/sold-A5400.jpg').read_bytes()
        return req('/api/staff/photos', 'POST', raw, owner, headers={'Content-Type': 'image/jpeg'})['path']

    image, cover = photo(), photo()
    original = listing('A5434')
    post('inventory', {**original['bus'], 'version': 0, 'action': 'draft'}, status=409)
    form = dict(stock='QAREGRESSION', title='2018 Chevrolet Express Shuttle Bus', price=22344.44,
                description='Sample inventory editor test', seats='8 passengers', lift='', miles='47000',
                luggage='', video='', nonCdl=True, wheelchairPositions=0, passengerSeats=8,
                inventoryType='shuttle-van', images=[image], version=0, action='draft', vin='1ftne1el0dda12345')
    post('inventory', {**form, 'price': 23.456}, status=400)
    post('inventory', form)
    bus = listing(form['stock'])['bus']
    assert (bus['make'], bus['year'], bus['vin']) == ('Chevrolet', 2018, '1FTNE1EL0DDA12345')
    req(image, status=404)
    req('/inventory/qaregression/', status=404)
    req('/api/subscribers', 'POST', {'email': 'arrival@example.invalid', 'language': 'en'})
    assert post('inventory', {**form, 'version': 1, 'action': 'publish_notify'})['queued'] >= 1
    assert post('inventory', {**form, 'version': 2, 'action': 'publish_notify'})['queued'] == 0
    assert any(row['stock'] == form['stock'] for row in req('/api/inventory')['rows'])
    post('inventory', {**form, 'version': 3, 'action': 'draft', 'description': 'Private unsent edit'})
    for action, version, state in [('trash', 4, 'trash-active'), ('restore', 5, 'active')]:
        result = post('inventory', dict(stock=form['stock'], action=action, version=version))
        assert result['state'] == state and result['queued'] == 0
        if action == 'trash':
            req('/inventory/qaregression/', status=404)
            req(image, status=404)
            assert not any(row['stock'] == form['stock'] for row in req('/api/inventory')['rows'])
            assert '/inventory/qaregression/' not in req('/sitemap.xml')
    with sqlite3.connect(database) as db:
        assert db.execute("SELECT DISTINCT state FROM bus_delivery WHERE stock=?", (form['stock'],)).fetchall() == [('cancelled',)]
    assert listing(form['stock'])['bus']['description'] == 'Private unsent edit'
    assert 'Private unsent edit' not in req('/inventory/qaregression/')
    post('inventory', {**form, 'action': 'sold', 'soldCover': cover, 'version': 6})
    assert any(row['stock'] == form['stock'] for row in req('/api/staff/accounting', c=accountant)['rows'])
    assert req(cover)
    mark('New stock, VIN and vehicle type, private photographs, one-time arrival queue, Trash and Restore, separate sold cover and accounting')

    gallery = req('/api/staff/gallery', c=owner)
    stock_cards = gallery['gallery']['items']
    assert len(stock_cards) == 20
    wanted = ['new-york', 'accessible-seniors', 'accessible-transit']
    assert [card['id'] for card in stock_cards[:3]] == wanted
    assert stock_cards[-1]['id'] == 'delivery-carrier'
    for lang in ['/', '/?lang=es']:
        page = req(lang)
        assert 'id="pizza-views"' not in page and 'pizza-cutout' not in page
        assert page.index('data-art="new-york"') < page.index('data-art="accessible-seniors"') < page.index('data-art="accessible-transit"') < page.index('data-art="pizza-outdoors"')
    pic = photo()
    item = dict(id=pic.rsplit('/', 1)[-1], src=pic, title='Sample gallery shuttle', titleEs='Autobús de muestra',
                alt='Sample shuttle photo', altEs='Foto de muestra', facing='right', group='community')
    form = dict(area='gallery', items=[item, *gallery['gallery']['items']], version=0, edition=69)
    post('gallery', {**form, 'edition': 63}, status=409)
    post('gallery', {**form, 'items': [item, item]}, status=400)
    post('gallery', form)
    post('gallery', form, status=409)
    assert req(pic) and 'Sample gallery shuttle' in req('/') and 'Autobús de muestra' in req('/?lang=es')
    post('gallery', {**form, 'items': gallery['gallery']['items'], 'version': 1})
    req(pic, status=404)
    # A v68 gallery may have missing defaults, manual captions and uploaded cards.
    # Its stored order used to be displayed in two facing-direction groups.
    by_id = {card['id']: card for card in stock_cards}
    old_fleet = {**by_id['fleet-lineup'], 'src':'/inspiration/fleet-lineup.webp', 'alt':'Custom saved text'}
    old_cards = [old_fleet, item, by_id['new-york'], by_id['accessible-seniors'], by_id['church']]
    with sqlite3.connect(database) as db:
        db.execute("UPDATE site_photo_galleries SET items=?,edition=63 WHERE area='gallery'", (json.dumps(old_cards),))
    state = req('/api/staff/gallery', c=owner)['gallery']
    ids = [card['id'] for card in state['items']]
    assert ids == ['new-york', item['id'], 'accessible-seniors', 'church', 'fleet-lineup']
    assert state['items'][-1]['src'] == by_id['fleet-lineup']['src'] and state['items'][-1]['alt'] == 'Custom saved text'
    saved = [state['items'][3], *state['items'][:3], state['items'][4]]
    post('gallery', {**form,'items':saved,'version':state['version']})
    assert req('/api/staff/gallery', c=owner)['gallery']['items'] == saved
    for lang in ['/', '/?lang=es']:
        page = req(lang)
        assert page.index('data-art="church"') < page.index('data-art="new-york"')
        assert 'Custom saved text' in page if lang=='/' else 'Operaciones de flota' in page
    post('gallery', {**form,'items':stock_cards,'version':state['version']+1})
    with sqlite3.connect(database) as db:
        old = dict(id='conversion-original', src='/photos/22933367_1.webp', title='Custom heading',
                   titleEs='Encabezado', alt='Ford E-350 flat-floor shuttle bus', altEs='Ford E-350 bus de transporte de pisos planos')
        db.execute("INSERT INTO site_photo_galleries(area,version,items,edition) VALUES('conversion',1,?,63)", (json.dumps([old]),))
    upgraded = req('/api/staff/gallery', c=owner)['conversion']['items'][0]
    assert upgraded['src'] == '/inspiration/conversion-outdoors.webp' and upgraded['title'] == old['title']
    mark('Gallery editor editions, saved legacy photo upgrades, public English and Spanish captions and removed photo privacy')

    src = req('/api/staff/blogs?id=topic-001', c=writer)['post']
    assert src['liveSpanish'] == 'provided' and src['bodyEs'] and src['hasSourceSpanish']
    form = dict(id=str(uuid.uuid4()), date='2026-02-01', title='A test shuttle article', cat='buying',
                summary='Accessible services.', body='Written for a local route.\n\nhttps://example.invalid/route\n\nA final paragraph.',
                bodyEs='', titleEs='', summaryEs='', action='draft', version=0)
    draft = post('blogs', form, writer)
    req(draft['path'], status=404)
    post('blogs', {**form, 'action': 'publish', 'version': 1}, writer, 403)
    live = post('blogs', {**form, 'action': 'publish', 'version': 1})
    assert live['path'] == draft['path'] and form['title'] in req(live['path'])
    job = bridge(2, 'translation-next', {})['job']
    assert job['id'] == form['id'] and not any('example.invalid' in v for v in job['texts'])
    bridge(2, 'translation-save', {**job, 'values': ['Traducción ' + t for t in job['texts']]})
    es = req('/es' + live['path'])
    assert 'Traducción' in es and 'https://example.invalid/route' in es
    check = req('/api/staff/blogs?id=' + form['id'], c=writer)['post']
    assert check['liveSpanish'] == 'automatic'
    bilingual = {**form, 'action': 'publish', 'titleEs': 'Un artículo', 'summaryEs': 'Un resumen', 'bodyEs': 'Texto revisado en español.'}
    post('blogs', {**bilingual, 'version': 2})
    assert bilingual['bodyEs'] in req('/es' + live['path'])
    bilingual['title'] = 'A changed English headline'
    post('blogs', {**bilingual, 'version': 3})
    assert bilingual['bodyEs'] not in req('/es' + live['path'])
    post('blogs', {**bilingual, 'version': 4, 'spanishReviewed': True})
    assert bilingual['bodyEs'] in req('/es' + live['path'])
    mark('Native Spanish archive in staff editor, writer draft, publication by sales, Google translation rehearsal, reviewed Spanish publication')
