"""2B.5: export job HTTP API. HTTP never generates, uploads, STARTs or acknowledges."""
from contextlib import closing
import hashlib
import json
import sqlite3
import threading
import uuid

import pytest

from InvestmentManager import scheduled_jobs
from InvestmentManager.integrator import domestic_batch, export_attempts as attempts
from InvestmentManager.integrator import export_arm, export_automation
from InvestmentManager.integrator import export_start
from InvestmentManager.integrator import export_control as control
from InvestmentManager.integrator import export_jobs as jobs
from InvestmentManager.integrator import portal_transport
from tests.investmentmanager import qualification_support as support

BASE = '/crm/offers/export-jobs'
GOOD = {'domain': 'domestic', 'subject': {'kind': 'offer', 'id': '17'}, 'portal': 'no', 'action': 'add',
        'package': {'mode': 'ensure_current'}}


@pytest.fixture
def api(client, tmp_path, monkeypatch):
    root = tmp_path / 'InvestmentData'
    root.mkdir()
    monkeypatch.setenv('DATA_DIR', str(root))
    support.init_root(root)
    assert jobs.init_schema(backup=False) == 'created'
    control.set_dispatch(True, changed_by='test')
    forbidden = lambda *a, **k: pytest.fail('HTTP reached generation/transport/START/ACK')
    for owner, name in ((portal_transport, 'upload_portal_zip'), (domestic_batch, 'process_offer'),
                        (export_start, 'start_qualified_transport'), (attempts, 'start_gated_transport'), (attempts, 'start_transport'),
                        (attempts, 'create_attempt'), (attempts, 'record_transport_result'),
                        (attempts, 'acknowledge_attempt'), (scheduled_jobs, 'tick')):
        monkeypatch.setattr(owner, name, forbidden)
    login(client)
    client.root = root
    return client


def login(client, level='master', user=7):
    with client.session_transaction() as session:
        session.clear()
        session['access_level'] = level
        if user is not None:
            session['user_id'] = user


def token(client, **kw):
    return client.get(BASE, **kw).json['csrf_token']


def post(client, url=BASE, body=GOOD, key=None, headers=None, csrf=True, **kw):
    headers = dict(headers or {})
    if csrf is True:
        headers.setdefault('X-Scheduler-CSRF', token(client))
    elif csrf:
        headers['X-Scheduler-CSRF'] = csrf
    if key is not False:
        headers.setdefault('Idempotency-Key', key or uuid.uuid4().hex)
    return client.post(url, json=body, headers=headers, **kw)


def create(client, subject='17', key=None, **kw):
    body = dict(GOOD, subject={'kind': 'offer', 'id': subject})
    return post(client, body=body, key=key, **kw)


def code(response):
    assert response.is_json and set(response.json) == {'error'} and set(response.json['error']) == {'code', 'message'}
    return response.json['error']['code']


def test_manual_mode_accepts_pl_and_foreign_without_enabling_automation_or_transport(api):
    """Dispatch opens the master UI for both domains; it does not arm FTP or enable automatic jobs."""
    assert control.dispatch_enabled() is True
    assert export_automation.read_config()['enabled'] is False
    assert export_arm.read()['status'] == 'missing'

    domestic = post(api, body=GOOD)
    foreign = post(api, body={
        'domain': 'foreign', 'subject': {'kind': 'foreign_offer', 'id': '11'},
        'portal': 'domiporta', 'action': 'add', 'package': {'mode': 'ensure_current'},
    })

    assert domestic.status_code == 202 and foreign.status_code == 202
    assert jobs.get_job(domestic.json['job_id'])['domain'] == 'domestic'
    assert jobs.get_job(foreign.json['job_id'])['domain'] == 'foreign'
    assert export_automation.read_config()['enabled'] is False
    assert export_arm.read()['status'] == 'missing'


def db_hash(client):
    """Logical content hash (immune to WAL checkpoint timing)."""
    result = {}
    for path in sorted((client.root / 'databases').glob('*.db')):
        with closing(sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True)) as conn:
            result[path.name] = hashlib.sha256('\n'.join(conn.iterdump()).encode('utf-8')).hexdigest()
    return result

def bulk(count, start=1000):
    with jobs._transaction(5) as conn:
        for number in range(count):
            jobs._insert(conn, dict(job_id=uuid.uuid4().hex, kind='delivery', domain='domestic', subject_kind='offer',
                                    subject_id=start + number, portal='no', action='add', package_mode='ensure_current',
                                    requested_package_id=None, planned_attempt_id=uuid.uuid4().hex), 'user:7', '{}', uuid.uuid4().hex)


# ------------------------------------------------------------ authorization
ROUTES = [('get', BASE), ('post', BASE), ('get', BASE + '/' + 'a' * 32), ('get', BASE + '/' + 'a' * 32 + '/events'),
          ('post', BASE + '/' + 'a' * 32 + '/cancel'), ('post', BASE + '/ack-recovery')]


@pytest.mark.parametrize('method,url', ROUTES)
@pytest.mark.parametrize('level', ['agent', 'admin', 'none'])
def test_only_master_with_a_user_id_may_use_any_route(api, method, url, level):
    before = db_hash(api)
    if level == 'none':
        login(api, 'master', user=None)
    else:
        login(api, level)
    response = getattr(api, method)(url, json={}, headers={'Idempotency-Key': uuid.uuid4().hex})
    assert response.status_code == 403
    if level != 'none':
        assert code(response) == 'forbidden'
    assert db_hash(api) == before


def test_unauthenticated_requests_get_the_blueprint_auth_error(client):
    response = client.get(BASE)
    assert response.status_code == 403 and response.json['code'] == 'auth_required'


def test_responses_are_never_cached_or_sniffed(api):
    for response in (api.get(BASE), api.get(BASE + '/zz'), post(api), api.get(BASE + '/' + 'a' * 32)):
        assert 'no-store' in response.headers['Cache-Control'] and response.headers['X-Content-Type-Options'] == 'nosniff'


# ---------------------------------------------------------------- CSRF/origin
@pytest.mark.parametrize('headers', [{}, {'X-Scheduler-CSRF': 'bad'}, {'X-Scheduler-CSRF': 'x' * 64}, {'X-Scheduler-CSRF': ''}])
def test_missing_or_wrong_csrf_fails_closed(api, headers):
    token(api)
    before = db_hash(api)
    response = api.post(BASE, json=GOOD, headers=dict(headers, **{'Idempotency-Key': uuid.uuid4().hex}))
    assert response.status_code == 403 and code(response) == 'csrf_failed' and db_hash(api) == before


def test_no_session_token_at_all_fails_closed(api):
    response = api.post(BASE, json=GOOD, headers={'X-Scheduler-CSRF': 'anything', 'Idempotency-Key': uuid.uuid4().hex})
    assert response.status_code == 403 and code(response) == 'csrf_failed'


@pytest.mark.parametrize('headers', [{'Origin': 'null'}, {'Origin': 'https://evil.invalid'}, {'Sec-Fetch-Site': 'cross-site'},
                                     {'Sec-Fetch-Site': 'same-site'}, {'Origin': 'http://evil.invalid', 'X-Forwarded-Host': 'evil.invalid'},
                                     {'Origin': 'https://evil.invalid', 'X-Forwarded-Host': 'evil.invalid', 'X-Forwarded-Proto': 'https'}])
def test_foreign_or_forged_origin_is_rejected(api, headers):
    response = post(api, headers=headers)
    assert response.status_code == 403 and code(response) == 'origin_forbidden'


@pytest.mark.parametrize('headers', [{}, {'Origin': 'http://localhost'}, {'Sec-Fetch-Site': 'same-origin'}, {'Sec-Fetch-Site': 'none'},
                                     {'Origin': 'http://localhost', 'Sec-Fetch-Site': 'same-origin'}])
def test_same_origin_variants_are_accepted(api, headers):
    assert post(api, headers=headers).status_code == 202


def test_https_origin_matches_only_the_effective_host_url(api):
    https = token(api, base_url='https://localhost')
    ok = api.post(BASE, base_url='https://localhost', json=GOOD, headers={'X-Scheduler-CSRF': https, 'Origin': 'https://localhost',
                                                                          'Idempotency-Key': uuid.uuid4().hex})
    assert ok.status_code == 202
    forged = api.post(BASE, json=dict(GOOD, subject={'kind': 'offer', 'id': '18'}), headers={
        'X-Scheduler-CSRF': https, 'Origin': 'https://localhost', 'X-Forwarded-Proto': 'https', 'Idempotency-Key': uuid.uuid4().hex})
    assert forged.status_code == 403 and code(forged) == 'origin_forbidden'      # plain-http request: header cannot upgrade it


# ----------------------------------------------------------- body strictness
def test_content_type_query_and_size_limits(api):
    headers = {'X-Scheduler-CSRF': token(api), 'Idempotency-Key': uuid.uuid4().hex}
    assert code(api.post(BASE, data=json.dumps(GOOD), headers=dict(headers, **{'Content-Type': 'text/plain'}))) == 'json_required'
    assert code(api.post(BASE + '?x=1', json=GOOD, headers=headers)) == 'invalid_request'
    padded = json.dumps(GOOD)
    exact = padded + ' ' * (8192 - len(padded))
    assert api.post(BASE, data=exact, headers=dict(headers, **{'Content-Type': 'application/json'})).status_code == 202
    over = padded + ' ' * (8193 - len(padded))
    response = api.post(BASE, data=over, headers=dict(headers, **{'Content-Type': 'application/json', 'Idempotency-Key': uuid.uuid4().hex}))
    assert response.status_code == 413 and code(response) == 'request_too_large'


@pytest.mark.parametrize('raw', ['{"domain":"domestic","domain":"foreign"}', '[]', '"x"', '{"a":NaN}', '{bad', '',
                                 '{"domain":"domestic","subject":{"kind":"offer","id":"1","id":"2"},"portal":"no","action":"add","package":{"mode":"ensure_current"}}'])
def test_malformed_duplicate_or_non_object_json_is_rejected(api, raw):
    response = api.post(BASE, data=raw, headers={'X-Scheduler-CSRF': token(api), 'Content-Type': 'application/json',
                                                 'Idempotency-Key': uuid.uuid4().hex})
    assert response.status_code == 400 and code(response) == 'invalid_request'


@pytest.mark.parametrize('mutation', [
    lambda b: b.update(actor='user:1'), lambda b: b.update(source='automation'), lambda b: b.update(members=[1]),
    lambda b: b.update(transport_profile='no'), lambda b: b.update(outcome='confirmed'), lambda b: b.update(can_send=True),
    lambda b: b.update(batch_id='a' * 32), lambda b: b.pop('package'), lambda b: b['subject'].update(extra=1),
    lambda b: b.update(portal='otodom'), lambda b: b.update(action='update'), lambda b: b['package'].update(package_id='a' * 32)])
def test_unknown_fields_and_invalid_combinations_are_rejected(api, mutation):
    body = json.loads(json.dumps(GOOD))
    mutation(body)
    response = post(api, body=body)
    assert response.status_code == 400 and code(response) in ('invalid_request', 'invalid_id')
    assert jobs.list_jobs()['items'] == []


@pytest.mark.parametrize('value,ok', [('7', True), ('9223372036854775807', True), (True, False), (1.5, False), (7, False), ('+1', False),
                                      (' 1', False), ('01', False), ('9223372036854775808', False), ('', False), ('-1', False), (None, False)])
def test_subject_id_is_a_strict_decimal_string(api, value, ok):
    response = post(api, body=dict(GOOD, subject={'kind': 'offer', 'id': value}))
    assert response.status_code == (202 if ok else 400)
    if not ok:
        assert code(response) == 'invalid_id'


@pytest.mark.parametrize('key', [False, 'abc', 'A' * 32, 'g' * 32, 'a' * 31])
def test_idempotency_key_is_required_hex32(api, key):
    response = post(api, key=key)
    assert response.status_code == 400 and code(response) == 'invalid_request'


# ------------------------------------------------------- create / idempotency
def test_accepted_response_location_and_replay(api):
    key = uuid.uuid4().hex
    first = create(api, key=key)
    assert first.status_code == 202
    body = first.json
    assert body['version'] == 1 and body['replayed'] is False and (body['kind'], body['state'], body['phase'], body['row_version']) == ('delivery', 'queued', 'accepted', 1)
    assert first.headers['Location'] == body['status_url'] == f'/crm{BASE[4:]}/{body["job_id"]}'
    again = create(api, key=key)
    assert again.status_code == 200 and again.json['replayed'] is True and again.json['job_id'] == body['job_id']
    assert 'Location' not in again.headers
    assert len(jobs.list_jobs()['items']) == 1


def test_replay_after_cancel_and_conflicts(api):
    key = uuid.uuid4().hex
    first = create(api, key=key).json
    cancelled = post(api, f'{BASE}/{first["job_id"]}/cancel', {}, headers={'If-Match': '"job-v1"'}, key=False)
    assert cancelled.status_code == 200
    replay = create(api, key=key)
    assert replay.status_code == 200 and replay.json['state'] == 'cancelled'
    other = post(api, body=dict(GOOD, subject={'kind': 'offer', 'id': '99'}), key=key)
    assert other.status_code == 409 and code(other) == 'idempotency_conflict'


def test_active_target_conflict_covers_both_actions(api):
    assert create(api).status_code == 202
    for action in ('add', 'delete'):
        response = post(api, body=dict(GOOD, action=action))
        assert response.status_code == 409 and code(response) == 'active_job_conflict'


def test_pause_blocks_new_intents_but_replay_still_reads(api):
    key = uuid.uuid4().hex
    first = create(api, key=key).json
    control.set_dispatch(False, changed_by='test')
    blocked = create(api, subject='18')
    assert blocked.status_code == 409 and code(blocked) == 'dispatch_paused'
    assert create(api, key=key).json['job_id'] == first['job_id']
    assert api.get(BASE).json['dispatch_enabled'] is False


def test_unknown_or_corrupt_control_is_fail_closed_for_new_intents(api):
    (api.root / 'scheduler' / control.NAME).write_text('{broken', encoding='utf8')
    listing = api.get(BASE).json
    assert listing['dispatch_enabled'] is None and listing['control_error'] == 'control_unavailable'
    assert code(create(api)) == 'dispatch_paused'


def test_commit_failure_never_returns_202_and_leaves_no_job(api, monkeypatch):
    with monkeypatch.context() as patch:
        patch.setattr(jobs, '_event', lambda *a, **k: (_ for _ in ()).throw(sqlite3.OperationalError('disk I/O error')))
        response = create(api)
    assert response.status_code == 503 and code(response) == 'storage_unavailable'
    assert jobs.list_jobs()['items'] == []


def test_missing_schema_is_a_503(client, tmp_path, monkeypatch):
    root = tmp_path / 'noschema'
    (root / 'databases').mkdir(parents=True)
    sqlite3.connect(root / 'databases/IDB.db').close()
    monkeypatch.setenv('DATA_DIR', str(root))
    login(client)
    response = client.get(BASE)
    assert response.status_code == 503 and code(response) == 'schema_unavailable'


def test_storage_thresholds_over_http(api, monkeypatch):
    key = uuid.uuid4().hex
    first = create(api, key=key).json
    sizes = {'physical': 48 * jobs.MiB}
    monkeypatch.setattr(jobs, '_storage_sizes', lambda path: (sizes['physical'], 0))
    blocked = create(api, subject='18')
    assert blocked.status_code == 503 and code(blocked) == 'job_storage_limit'
    assert create(api, key=key).status_code == 200                          # identical intent replays
    assert api.get(BASE).json['storage']['blocked'] is True
    cancel = post(api, f'{BASE}/{first["job_id"]}/cancel', {}, headers={'If-Match': '"job-v1"'}, key=False)
    assert cancel.status_code == 200
    sizes['physical'] = 40 * jobs.MiB + 4096
    assert api.get(BASE).json['storage'] == {'physical_bytes': sizes['physical'], 'used_bytes': sizes['physical'], 'free_bytes': 0, 'warn': True, 'blocked': False}


# -------------------------------------------------------------------- reads
def test_get_job_has_etag_attempt_observation_and_no_secrets(api):
    receipt = create(api).json
    response = api.get(f'{BASE}/{receipt["job_id"]}')
    assert response.status_code == 200 and response.headers['ETag'] == '"job-v1"'
    job = response.json['job']
    assert response.json['attempt'] is None and job['state'] == 'queued' and job['actor_ref'] == 'user:7'
    assert not {'owner_id', 'request_json', 'idempotency_key', 'request_sha256', '_internal'} & set(job)


def test_job_with_a_linked_attempt_shows_the_authoritative_state_and_unavailable_reads(api, monkeypatch):
    receipt = create(api).json
    claim = jobs.claim_next('delivery')
    with closing(sqlite3.connect(api.root / 'databases/IDB.db')) as conn, conn:
        conn.execute("INSERT INTO EstateData VALUES ('17','aktywna','T','mieszkanie')")
        package = support._domestic_attempt(conn, 17, 'no', 'add', ['prepared', 'transport_unknown'], attempt_id=claim.planned_attempt_id)
    binding = attempts.inspect_attempt(claim.planned_attempt_id)['attempt']['binding']
    jobs.advance(claim, phase='attempt_linked', references={'package_id': package, 'binding_sha256': jobs.binding_digest(binding),
                                                              'attempt_anchor_id': 17, 'attempt_id': claim.planned_attempt_id})
    observed = api.get(f'{BASE}/{receipt["job_id"]}').json
    assert observed['attempt']['state'] == 'transport_unknown' and observed['attempt']['members'] == [17] and isinstance(observed['attempt']['zip_name'], str) and observed['attempt']['zip_name'].endswith('.zip')
    assert observed['job']['state'] == 'running' and observed['attempt']['attempt_read'] == {'state': 'found'}
    real = attempts.inspect_attempt
    monkeypatch.setattr(attempts, 'inspect_attempt', lambda *a, **k: {'state': 'unavailable', 'attempt': None, 'reason': 'storage_unavailable'})
    degraded = api.get(f'{BASE}/{receipt["job_id"]}')
    assert degraded.status_code == 200 and degraded.json['attempt']['attempt_read']['state'] == 'unavailable'
    assert degraded.json['job']['phase'] == 'attempt_linked'


def test_reads_have_no_side_effects(api):
    first = create(api).json
    bulk(5)
    before = db_hash(api)
    for url in (BASE, f'{BASE}?limit=3', f'{BASE}/{first["job_id"]}', f'{BASE}/{first["job_id"]}/events', f'{BASE}?state=queued&kind=delivery&domain=domestic'):
        assert api.get(url).status_code == 200
    assert db_hash(api) == before


def test_list_pagination_by_seq_has_no_gaps_or_duplicates(api):
    bulk(250)
    for size in (100, 50, 1):
        seen, cursor = [], None
        while True:
            page = api.get(BASE + f'?limit={size}' + (f'&before={cursor}' if cursor else '')).json
            seen += [item['job_id'] for item in page['items']]
            cursor = page['next_cursor']
            if not cursor or len(seen) >= 250:
                break
        assert len(seen) == len(set(seen)) == 250
    page = api.get(BASE).json
    assert len(page['items']) == 50 and page['csrf_token'] and page['dispatch_enabled'] is True
    assert {'physical_bytes', 'warn', 'blocked'} <= set(page['storage'])
    assert not {'metrics', 'members', 'events'} & set(page['items'][0])


@pytest.mark.parametrize('query', ['?limit=0', '?limit=101', '?limit=abc', '?limit=1&limit=2', '?unknown=1', '?before=!!', '?state=nope',
                                   '?kind=x', '?domain=x', '?batch_id=zz', '?before=MA'])
def test_invalid_list_parameters(api, query):
    response = api.get(BASE + query)
    assert response.status_code == 400 and code(response) in ('invalid_request', 'invalid_cursor')


def test_events_endpoint(api):
    first = create(api).json
    jobs.claim_next('delivery')
    page = api.get(f'{BASE}/{first["job_id"]}/events?limit=1').json
    assert page['more'] is True and [e['event_type'] for e in page['items']] == ['accepted'] and page['truncated'] is False
    rest = api.get(f'{BASE}/{first["job_id"]}/events?after={page["next_after"]}').json
    assert [e['event_type'] for e in rest['items']] == ['claimed'] and not rest['more']
    for bad in ('?after=-1', '?limit=0', '?limit=101', '?after=x', '?limit=1&limit=2', '?x=1'):
        assert api.get(f'{BASE}/{first["job_id"]}/events{bad}').status_code == 400
    assert api.get(f'{BASE}/{"e" * 32}/events').status_code == 404
    assert api.get(f'{BASE}/not-an-id/events').status_code == 400


def test_get_job_validation(api):
    assert code(api.get(f'{BASE}/zzz')) == 'invalid_id'
    assert code(api.get(f'{BASE}/{"e" * 32}')) == 'job_not_found'
    assert code(api.get(f'{BASE}/{"a" * 32}?x=1')) == 'invalid_request'


# ------------------------------------------------------------------- cancel
def cancel(api, job_id, etag='"job-v1"', body={}, **kw):
    headers = {} if etag is None else {'If-Match': etag}
    return post(api, f'{BASE}/{job_id}/cancel', body, headers=headers, key=False, **kw)


def test_cancel_preconditions_and_idempotent_repeat(api):
    job = create(api).json['job_id']
    assert code(cancel(api, job, None)) == 'precondition_required' and cancel(api, job, None).status_code == 428
    assert cancel(api, job, 'job-v1').status_code == 400 and cancel(api, job, '"job-vx"').status_code == 400
    stale = cancel(api, job, '"job-v9"')
    assert stale.status_code == 412 and code(stale) == 'job_version_conflict'
    done = cancel(api, job)
    assert done.status_code == 200 and done.json['job']['state'] == 'cancelled' and done.headers['ETag'] == '"job-v2"'
    events = api.get(f'{BASE}/{job}/events').json['items']
    repeat, stale_repeat = cancel(api, job), cancel(api, job, '"job-v77"')
    assert repeat.status_code == stale_repeat.status_code == 200
    assert api.get(f'{BASE}/{job}/events').json['items'] == events and events[-1]['event_type'] == 'cancelled'
    assert cancel(api, 'e' * 32).status_code == 404 and cancel(api, 'zz').status_code == 400
    assert cancel(api, job, body={'x': 1}).status_code == 400


def test_cancel_refuses_running_jobs(api):
    job = create(api).json['job_id']
    claim = jobs.claim_next('delivery')
    response = cancel(api, job, f'"job-v{claim.row_version}"')
    assert response.status_code == 409 and code(response) == 'job_not_queued'
    assert api.get(f'{BASE}/{job}').json['job']['state'] == 'running'


@pytest.mark.parametrize('state,status', [('prepared', 200), ('transport_unknown', 409), ('transport_confirmed', 409), ('ack_rejected', 409)])
def test_cancel_of_a_requeued_job_depends_on_its_attempt(api, state, status):
    receipt = create(api).json
    claim = jobs.claim_next('delivery')
    path = {'prepared': ['prepared'], 'transport_unknown': ['prepared', 'transport_unknown'],
            'transport_confirmed': ['prepared', 'transport_unknown', 'transport_confirmed'],
            'ack_rejected': ['prepared', 'transport_unknown', 'transport_confirmed', 'ack_rejected']}[state]
    with closing(sqlite3.connect(api.root / 'databases/IDB.db')) as conn, conn:
        package = support._domestic_attempt(conn, 17, 'no', 'add', path, attempt_id=claim.planned_attempt_id)
    binding = attempts.inspect_attempt(claim.planned_attempt_id)['attempt']['binding']
    claim = jobs.advance(claim, phase='attempt_linked', references={'package_id': package, 'binding_sha256': jobs.binding_digest(binding),
                                                                      'attempt_anchor_id': 17, 'attempt_id': claim.planned_attempt_id})
    jobs.advance(claim, state='queued', phase='paused')
    version = jobs.get_job(receipt['job_id'])['row_version']
    response = cancel(api, receipt['job_id'], f'"job-v{version}"')
    assert response.status_code == status
    if status == 409:
        assert code(response) == 'job_not_queued'


def test_cancel_versus_claim_race_has_one_winner(api):
    for number in range(30):
        job = create(api, subject=str(500 + number)).json
        barrier = threading.Barrier(2)
        out = {}

        def claimer():
            barrier.wait()
            out['claim'] = jobs.claim_next('delivery')
        thread = threading.Thread(target=claimer)
        thread.start()
        barrier.wait()
        response = cancel(api, job['job_id'])
        thread.join()
        claimed = out['claim'] is not None and out['claim'].job_id == job['job_id']
        assert (response.status_code == 200) != claimed or response.status_code == 503
        if response.status_code == 503:                                       # input lock busy: nothing was confirmed
            assert api.get(f'{BASE}/{job["job_id"]}').json['job']['state'] in ('queued', 'running')
        if claimed:
            jobs.advance(out['claim'], state='completed', reason_code='x')
    assert jobs.verify_integrity() == []


# ------------------------------------------------------------------ ack-only
def attempt_in(api, path, subject=17, portal='no'):
    attempt_id = uuid.uuid4().hex
    with closing(sqlite3.connect(api.root / 'databases/IDB.db')) as conn, conn:
        support._domestic_attempt(conn, subject, portal, 'add', path, attempt_id=attempt_id)
    return attempt_id


def ack(api, attempt_id, domain='domestic', **kw):
    return post(api, f'{BASE}/ack-recovery', {'domain': domain, 'attempt_id': attempt_id}, **kw)


STATES = {'prepared': ['prepared'], 'transport_unknown': ['prepared', 'transport_unknown'],
          'transport_failed': ['prepared', 'transport_unknown', 'transport_failed'],
          'ack_rejected': ['prepared', 'transport_unknown', 'transport_confirmed', 'ack_rejected'],
          'transport_confirmed': ['prepared', 'transport_unknown', 'transport_confirmed'],
          'ack_failed': ['prepared', 'transport_unknown', 'transport_confirmed', 'ack_failed'],
          'ack_completed': ['prepared', 'transport_unknown', 'transport_confirmed', 'ack_completed']}


@pytest.mark.parametrize('state', list(STATES))
def test_ack_recovery_accepts_only_recoverable_states(api, state):
    attempt_id = attempt_in(api, STATES[state])
    response = ack(api, attempt_id)
    if state in ('transport_confirmed', 'ack_failed', 'ack_completed'):
        assert response.status_code == 202 and response.json['kind'] == 'ack_only'
    else:
        assert response.status_code == 409 and code(response) == 'ack_not_recoverable'
        assert jobs.list_jobs()['items'] == []


def test_queued_ack_only_job_can_be_cancelled_although_its_attempt_is_confirmed(api):
    # A queued ACK-only job has started nothing; the delivery-attempt guard must not apply to it.
    attempt_id = attempt_in(api, STATES['transport_confirmed'])
    job = ack(api, attempt_id).json['job_id']
    response = cancel(api, job, '"job-v1"')
    assert response.status_code == 200 and response.json['job']['state'] == 'cancelled'
    assert jobs.verify_integrity() == []


def test_ack_recovery_replay_unknown_and_invalid_targets(api):
    attempt_id = attempt_in(api, STATES['transport_confirmed'])
    key = uuid.uuid4().hex
    first = ack(api, attempt_id, key=key)
    assert first.status_code == 202
    again = ack(api, attempt_id, key=key)
    assert again.status_code == 200 and again.json['job_id'] == first.json['job_id']
    assert code(ack(api, attempt_id)) == 'active_job_conflict'
    assert code(ack(api, 'e' * 32)) == 'attempt_not_found' and ack(api, 'e' * 32).status_code == 404
    assert code(ack(api, 'zz')) == 'invalid_id'
    assert code(post(api, f'{BASE}/ack-recovery', {'domain': 'x', 'attempt_id': attempt_id})) == 'invalid_request'
    assert code(post(api, f'{BASE}/ack-recovery', {'domain': 'domestic', 'attempt_id': attempt_id, 'binding': {}})) == 'invalid_request'
    assert ack(api, attempt_id, domain='foreign').status_code in (404, 503)


def test_ack_recovery_links_the_parent_delivery_and_refuses_while_it_runs(api):
    receipt = create(api).json
    claim = jobs.claim_next('delivery')
    attempt_id = attempt_in(api, STATES['transport_confirmed'])
    with closing(sqlite3.connect(api.root / 'databases/IDB.db')) as conn, conn:
        conn.execute("INSERT INTO EstateData VALUES ('17','aktywna','T','mieszkanie')")
    binding = attempts.inspect_attempt(attempt_id)['attempt']['binding']
    claim = jobs.advance(claim, phase='attempt_linked', references={'package_id': binding['package_id'], 'attempt_anchor_id': 17,
                                                                      'binding_sha256': jobs.binding_digest(binding), 'attempt_id': attempt_id})
    running = ack(api, attempt_id)
    assert running.status_code == 409 and code(running) == 'delivery_in_progress'
    jobs.advance(claim, state='needs_review', reason_code='ack_pending')
    accepted = ack(api, attempt_id)
    assert accepted.status_code == 202
    assert api.get(f'{BASE}/{accepted.json["job_id"]}').json['job']['parent_job_id'] == receipt['job_id']


def test_ack_recovery_is_available_when_paused_or_storage_is_full(api, monkeypatch):
    attempt_id = attempt_in(api, STATES['ack_failed'])
    control.set_dispatch(False, changed_by='test')
    monkeypatch.setattr(jobs, '_storage_sizes', lambda path: (60 * jobs.MiB, 0))
    assert ack(api, attempt_id).status_code == 202


# -------------------------------------------------------- redaction / safety
def test_unexpected_errors_never_leak_details(api, monkeypatch):
    monkeypatch.setattr(jobs, 'list_jobs', lambda **k: (_ for _ in ()).throw(RuntimeError('secret C:\\private\\path password=hunter2')))
    response = api.get(BASE)
    assert response.status_code == 503 and code(response) == 'storage_unavailable'
    assert 'hunter2' not in response.get_data(as_text=True) and 'private' not in response.get_data(as_text=True)


def test_stored_text_is_returned_as_data_not_markup(api):
    receipt = create(api).json
    claim = jobs.claim_next('delivery')
    jobs.advance(claim, state='blocked', reason_code='qualification_changed', details={'note': '<script>alert(1)</script>'})
    events = api.get(f'{BASE}/{receipt["job_id"]}/events')
    assert events.mimetype == 'application/json' and '<script>' in events.get_data(as_text=True)    # JSON-encoded, never HTML
    assert api.get(f'{BASE}/{receipt["job_id"]}').mimetype == 'application/json'


def test_http_can_not_forge_actor_or_outcome(api):
    response = post(api, body=dict(GOOD, actor='user:99', outcome='confirmed', can_send=True))
    assert response.status_code == 400
    ok = create(api).json
    assert api.get(f'{BASE}/{ok["job_id"]}').json['job']['actor_ref'] == 'user:7'
    login(api, user=12)
    other = create(api, subject='33').json
    assert api.get(f'{BASE}/{other["job_id"]}').json['job']['actor_ref'] == 'user:12'


def test_same_key_from_another_master_is_a_separate_namespace(api):
    key = uuid.uuid4().hex
    first = create(api, key=key).json
    login(api, user=12)
    second = create(api, subject='34', key=key)
    assert second.status_code == 202 and second.json['job_id'] != first['job_id']
    assert api.get(f'{BASE}/{first["job_id"]}').status_code == 200            # history is readable by any master


def test_blocked_job_frees_the_target_for_a_new_conscious_intent(api):
    first = create(api).json
    claim = jobs.claim_next('delivery')
    jobs.advance(claim, state='blocked', reason_code='qualification_changed')
    assert create(api).status_code == 202
    assert first['job_id'] != api.get(BASE).json['items'][0]['job_id']
