"""Repeatable public CLI setup for the independent Chapter 18 teaching namespace."""
from chapter18_support import *
from importlib.util import spec_from_file_location, module_from_spec

spec = spec_from_file_location('prepare_chapter18', LAB/'checks/prepare-chapter-18.py')
fixture = module_from_spec(spec); spec.loader.exec_module(fixture); fixture.prepare()
e = new_run(); save(e/'hashes-before.json', hashes())
cap = call(e, 'capabilities', 'capabilities')
assert cap['engine'] == 'java' and cap['data']['securityMode'] == 'none-dev-test-only'
name = 'chinook-calendar-sqlite'
jdbc = 'jdbc:sqlite:'+str(PROJECT/'data/calendar-teaching.sqlite').replace('\\','/')
listed = call(e, 'datasources-before', 'datasources', 'list')['data']['datasources']
existing = next((d for d in listed if d['name'] == name), None)
if existing:
    assert existing['jdbcUrl'] == jdbc, 'Existing datasource points elsewhere; do not replace it.'
else:
    call(e, 'datasource-add', 'datasources', 'add', '--name', name, '--type', 'sqlite', '--jdbc-url', jdbc)
call(e, 'datasource-test', 'datasources', 'test', name)
call(e, 'datasource-bind', 'datasources', 'bind', '--namespace', NS, '--data-source', name)
call(e, 'binding', 'datasources', 'binding', '--namespace', NS)
call(e, 'tables', 'tables', 'list', '--data-source', name)
for table in ['TeachingInvoice','ReportingCalendar']:
    call(e, 'inspect-'+table, 'tables', 'inspect', '--data-source', name, '--table', table, '--include-indexes')
call(e, 'models-validate-final', 'models', 'validate', '--models-dir', PROJECT/'models', '--include-stack-trace')
call(e, 'bundle-register', 'bundles', 'add', '--name', 'chinook-calendar-teaching', '--path', PROJECT/'models', '--replace')
call(e, 'refresh-final', 'models', 'refresh')
for model in ['TeachingInvoiceDatesQueryModel','TeachingCalendarReportQueryModel']:
    call(e, 'metadata-'+model, 'models', 'describe', model)
    result = call(e, 'markdown-'+model, 'models', 'describe', model, '--format', 'markdown')
    (e/(model+'.md')).write_text(result['data']['content'], encoding='utf-8')
save(e/'model-source-files.json', {str(p.relative_to(PROJECT)):p.read_text(encoding='utf-8') for p in (PROJECT/'models').rglob('*') if p.is_file()})
print('Models ready; business queries have not run. Evidence:', e)
