"""Import and validate a synthetic v68 dealership snapshot without changing the source."""
import hashlib
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import tempfile
import uuid

root = Path(__file__).resolve().parents[1]
with tempfile.TemporaryDirectory() as scratch:
    folder = Path(scratch)
    source = folder/'v68.sqlite'
    photos = folder/'photos'
    photos.mkdir()
    photo_id = str(uuid.uuid4())
    sample = next((root/'public/photos').glob('*.jpg')).read_bytes()
    stock = 'A5352'
    ref = '/api/bus-photo/'+photo_id
    listing = json.dumps({'stock':stock, 'title':'Transfer test bus','images':[ref]})
    with sqlite3.connect(source) as old:
        for migration in sorted((root/'database/schema').glob('*.sql')):
            old.executescript(migration.read_text())
        old.execute('INSERT INTO bus_inventory VALUES (?,?,?,?,?,?,?)',(stock,listing,listing,'active',4,'fixture','2026-01-01'))
        old.execute('INSERT INTO bus_delivery VALUES (?,?,?,?,?)',(stock,'test@example.invalid','sending','old-claim','2026-01-01'))
        old.execute('INSERT INTO bus_sender(id,key_hash,mailbox,enabled) VALUES (1,?,?,1)',('old-digest','test@example.invalid'))
        old.execute("INSERT INTO bus_staff_disabled VALUES ('greatbusesforsale@gmail.com')")
        old.execute('CREATE TABLE host_passwords(test_hash TEXT)')
        old.execute("INSERT INTO host_passwords VALUES ('private-example')")
    old.close()
    before = hashlib.sha256(source.read_bytes()).digest()
    output = folder/'converted'
    cmd = ['php','tools/private-data.php','import-v68',str(source),str(photos),str(output)]
    missing = subprocess.run(cmd,cwd=root,capture_output=True,check=False)
    assert missing.returncode and b'missing an object' in missing.stderr and not output.exists(),missing.stderr
    (photos/photo_id).write_bytes(sample)
    subprocess.run(cmd,cwd=root,check=True)
    assert subprocess.run(cmd,cwd=root,capture_output=True).returncode != 0
    assert hashlib.sha256(source.read_bytes()).digest()==before
    assert sample == (output/'photos'/photo_id).read_bytes()
    for line in (output/'SHA256SUMS').read_text().splitlines():
        expected, name = line.split('  ')
        assert expected==hashlib.sha256((output/name).read_bytes()).hexdigest()
    dbpath=output/'database.sqlite'
    env={**os.environ,'DB_DATABASE':str(dbpath),'DB_CONNECTION':'sqlite','APP_ENV':'testing'}
    subprocess.run(['php','artisan','dealer:install'],cwd=root,env=env,check=True,stdout=subprocess.DEVNULL)
    with sqlite3.connect(dbpath) as new:
        assert new.execute('SELECT version,live FROM bus_inventory').fetchone()==(4,listing)
        assert new.execute('SELECT state,claim FROM bus_delivery').fetchone()==('review',None)
        enabled,digest = new.execute('SELECT enabled,key_hash FROM bus_sender').fetchone()
        assert enabled==0 and digest !='old-digest'
        assert new.execute("SELECT enabled FROM laravel_staff WHERE email='greatbusesforsale@gmail.com'").fetchone()==(0,)
        assert new.execute("SELECT count(*) FROM sqlite_schema WHERE name='host_passwords'").fetchone()==(0,)
        assert new.execute('PRAGMA integrity_check').fetchone()==('ok',)
    print('PASS v68 database import, missing-photo rollback, no overwrite, historical version and photo checksums, disabled access and paused sender.')
