"""Stage 4: optional automatic job creation. OFF by default; creates only queued jobs; every guard-rail holds."""
from contextlib import closing
import json
import sqlite3
import uuid

import pytest

from InvestmentManager import scheduled_jobs
from InvestmentManager.integrator import export_automation as auto
from InvestmentManager.integrator import export_control as control
from InvestmentManager.integrator import export_job_runner as runner
from InvestmentManager.integrator import export_jobs as jobs
from InvestmentManager.integrator import package_delivery as pd
from tests.investmentmanager import qualification_support as support

ACTOR = 'user:7'


@pytest.fixture
def box(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')
    return root


@pytest.fixture
def stub(monkeypatch):
    calls = []

    def run(claim, env=None):
        calls.append((claim.kind, claim.job_id, claim.source))
        pd._advance(pd.Env(), claim, state='completed', reason_code='stub')
        return pd.DeliveryOutcome('completed', 'stub')
    monkeypatch.setattr(pd, 'execute_delivery', run)
    monkeypatch.setattr(pd, 'execute_ack_only', run)
    return calls


def task(subject=10, portal='no', category='new', action='add', issue=None, last=None, domain='domestic'):
    kind = 'offer' if domain == 'domestic' else 'foreign_offer'
    return {'domain': domain, 'subject': {'kind': kind, 'id': subject}, 'portal': portal, 'action': action,
            'category': category, 'issue': issue, 'last_result': last, 'offer_ids': [subject]}


def queue(*tasks):
    def rows_fn(*, max_rows, settings):
        return {'items': list(tasks)[:max_rows], 'total': len(tasks)}
    return rows_fn


def enable(**kw):
    kw.setdefault('portals', ['no', 'domiporta'])
    return auto.enable(changed_by='test', **kw)


def again():
    """Forget the frequency gate (not the durable job store, which holds the real guard-rails)."""
    path = scheduled_jobs._directory() / auto.STATE
    if path.exists():
        path.unlink()


def go(*tasks, **kw):
    return auto.run(rows_fn=queue(*tasks), destination_ok=lambda t: True, **kw)


def autos():
    return [j for j in jobs.list_jobs(limit=100)['items'] if j.get('source') == 'automation'] if False else \
        _rows("SELECT job_id,state,source,actor_ref,policy_id,policy_version,slot_key,subject_id,portal FROM export_jobs WHERE source='automation' ORDER BY seq")


def _rows(sql):
    with jobs._reader(jobs.WORKER_TIMEOUT) as conn:
        return [dict(zip([c[0] for c in conn.execute(sql).description], row)) for row in conn.execute(sql)]


def finish(job_id, state, reason='x'):
    claim = jobs.claim_next('delivery')
    assert claim.job_id == job_id
    jobs.advance(claim, state=state, reason_code=reason)


# ------------------------------------------------------------------ OFF by default
def test_everything_is_off_without_explicit_configuration(box, stub):
    assert auto.read_config() == {'status': 'missing', 'enabled': False, 'config': None}
    assert auto.run(rows_fn=queue(task()), destination_ok=lambda t: True)['outcome'] == 'disabled'
    result = runner.tick_one(env=None)
    assert 'automation' not in result and result['outcome'] == 'idle'          # tick response unchanged while OFF
    assert _rows('SELECT COUNT(*) AS n FROM export_jobs')[0]['n'] == 0
    assert not (scheduled_jobs._directory() / auto.NAME).exists() and not (scheduled_jobs._directory() / auto.STATE).exists()
    assert control.read()['automation_enabled'] is False


def test_enable_requires_explicit_valid_portals_and_limits(box):
    for bad in ({'portals': []}, {'portals': ['otodom']}, {'portals': ['no', 'no']}, {'portals': 'no'},
                {'portals': ['no'], 'categories': ['error']}, {'portals': ['no'], 'max_per_run': 0},
                {'portals': ['no'], 'max_per_run': 11}, {'portals': ['no'], 'min_interval_seconds': 10},
                {'portals': ['no'], 'policy_id': 'Bad Id'}, {'portals': ['no'], 'bogus': 1}):
        with pytest.raises(ValueError):
            auto.enable(**bad)
    assert auto.read_config()['status'] == 'missing'
    state = enable(portals=['no'])
    assert state['enabled'] and state['config']['policy_version'] == 1 and state['config']['categories'] == ['new', 'update']
    assert enable(portals=['no'])['config']['policy_version'] == 2        # a new policy never reuses old slots
    assert auto.disable(changed_by='test')['enabled'] is False


def test_corrupt_or_foreign_config_is_off(box):
    path = scheduled_jobs._directory(create=True) / auto.NAME
    for text in ('{', '[]', json.dumps({'version': 1}), json.dumps({'enabled': True})):
        path.write_text(text)
        assert auto.read_config()['status'] == 'corrupt' and auto.read_config()['enabled'] is False
        assert go(task())['outcome'] == 'disabled'


# ------------------------------------------------------------------ creation
def test_creates_only_queued_automation_jobs_with_audit(box):
    enable(portals=['no'])
    summary = go(task(10), task(11), task(12))
    assert summary['outcome'] == 'created' and summary['created'] == 2          # max_per_run default 2
    rows = autos()
    assert [r['subject_id'] for r in rows] == [10, 11]
    assert all(r['state'] == 'queued' and r['actor_ref'] == 'policy:auto' and r['policy_id'] == 'auto'
               and r['policy_version'] == 1 and r['slot_key'] for r in rows)
    first = jobs.list_events(rows[0]['job_id'])['items'][0]
    assert first['event_type'] == 'accepted' and first['actor_ref'] == 'policy:auto'
    assert first['details']['automation'] == {'policy_id': 'auto', 'policy_version': 1, 'slot': rows[0]['slot_key']}
    state = auto.read_state()
    assert state['status'] == 'ok' and state['runs'][-1]['created'] == 2 and state['runs'][-1]['skipped'] == {}
    assert go(task(10), task(11), task(12))['outcome'] == 'not_due'


def test_manual_jobs_are_independent_of_automation(box):
    enable(portals=['no'])
    manual = jobs.create_delivery({'domain': 'domestic', 'subject': {'kind': 'offer', 'id': 40}, 'portal': 'no', 'action': 'add',
                                   'package': {'mode': 'ensure_current'}}, actor=ACTOR, idempotency_key=uuid.uuid4().hex,
                                  dispatch_enabled=True)
    assert manual.state == 'queued'
    go(task(41))
    sources = {r['subject_id']: r['source'] for r in _rows('SELECT subject_id,source FROM export_jobs')}
    assert sources == {40: 'manual', 41: 'automation'}
    auto.disable(changed_by='test')
    assert jobs.get_job(manual.job_id)['state'] == 'queued'                        # disabling never touches manual jobs


@pytest.mark.parametrize('row,reason', [
    (task(issue='source_offer_missing'), 'queue_issue'),
    (task(category='error'), 'queue_issue'),
    (task(portal='tabelaofert'), 'portal_not_enabled'),
    (task(category='withdraw', action='delete'), 'category_not_enabled'),
    (task(last={'state': 'transport_unknown'}), 'unresolved_or_unfinished_attempt'),
    (task(last={'state': 'ack_rejected'}), 'unresolved_or_unfinished_attempt'),
    (task(last={'state': 'transport_confirmed', 'can_ack': True}), 'unresolved_or_unfinished_attempt'),
    (task(last={'state': 'ack_failed'}), 'unresolved_or_unfinished_attempt'),
    (task(last={'state': 'prepared'}), 'unresolved_or_unfinished_attempt'),
])
def test_never_creates_for_unsafe_units(box, row, reason):
    enable(portals=['no'])
    summary = go(row)
    assert summary['outcome'] == 'nothing_to_do' and summary['skipped'] == {reason: 1} and autos() == []


def test_destination_unconfigured_is_skipped(box):
    enable(portals=['no'])
    summary = auto.run(rows_fn=queue(task()), destination_ok=lambda t: False)
    assert summary['skipped'] == {'destination_unconfigured': 1} and autos() == []


def test_active_job_unit_is_skipped_including_needs_review(box):
    enable(portals=['no'])
    go(task(10))
    again()
    assert go(task(10))['skipped'] == {'active_job': 1}
    job = autos()[0]['job_id']
    claim = jobs.claim_next('delivery')
    jobs.advance(claim, state='needs_review', reason_code='transport_unknown')       # UNKNOWN reserves the unit
    again()
    summary = go(task(10))
    assert summary['skipped'] == {'active_job': 1} and len(autos()) == 1 and autos()[0]['job_id'] == job


def test_no_automatic_retry_after_a_failed_attempt_within_the_cooldown(box):
    enable(portals=['no'])
    go(task(10))
    finish(autos()[0]['job_id'], 'failed', 'transport_failed')
    again()
    summary = go(task(10))
    assert summary['skipped'] == {'cooldown': 1} and len(autos()) == 1
    blocked = jobs.create_delivery({'domain': 'domestic', 'subject': {'kind': 'offer', 'id': 20}, 'portal': 'no', 'action': 'add',
                                    'package': {'mode': 'ensure_current'}}, actor=ACTOR, idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)
    finish(blocked.job_id, 'blocked', 'qualification_changed')
    again()
    assert go(task(20))['skipped'] == {'cooldown': 1}                                  # manual failures cool the unit too
    # after the cooldown a certain failure may be retried (never after UNKNOWN: that unit stays reserved)
    again()
    far = jobs.clock() + 2 * 86400
    summary = auto.run(rows_fn=queue(task(20)), destination_ok=lambda t: True, now=far)
    assert summary['outcome'] == 'created'


# ------------------------------------------------------------------ limits
def test_limits_per_run_day_and_active(box):
    enable(portals=['no'], max_per_run=3, max_per_day=4, max_active=10)
    assert go(*[task(n) for n in range(1, 8)])['created'] == 3
    again()
    assert go(*[task(n) for n in range(1, 8)])['created'] == 1                          # day budget 4 - 3
    again()
    assert go(*[task(n) for n in range(1, 8)])['outcome'] == 'limit_reached'
    assert len(autos()) == 4


def test_max_active_counts_every_pending_job_of_any_source(box):
    enable(portals=['no'], max_per_run=5, max_active=2)
    jobs.create_delivery({'domain': 'domestic', 'subject': {'kind': 'offer', 'id': 99}, 'portal': 'no', 'action': 'add',
                          'package': {'mode': 'ensure_current'}}, actor=ACTOR, idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)
    assert go(*[task(n) for n in range(1, 6)])['created'] == 1
    again()
    assert go(*[task(n) for n in range(1, 6)])['outcome'] == 'limit_reached'


def test_minimum_interval_between_runs(box):
    enable(portals=['no'], min_interval_seconds=600)
    assert go(task(1))['outcome'] == 'created'
    assert go(task(2))['outcome'] == 'not_due'
    assert len(autos()) == 1
    now = jobs.clock() + 601
    assert auto.run(rows_fn=queue(task(2)), destination_ok=lambda t: True, now=now)['outcome'] == 'created'


def test_circuit_breaker_after_repeated_failures(box):
    enable(portals=['no'], max_per_run=1, breaker_failures=2, max_per_day=50)
    for number in (1, 2):
        go(task(number))
        finish(autos()[-1]['job_id'], 'failed', 'transport_failed')
        again()
    summary = go(task(3))
    assert summary['outcome'] == 'circuit_open' and len(autos()) == 2


def test_dispatch_paused_or_unreadable_creates_nothing(box):
    enable(portals=['no'])
    control.set_dispatch(False, changed_by='test')
    assert go(task(1))['outcome'] == 'dispatch_off'
    (scheduled_jobs._directory() / control.NAME).write_text('{')
    assert go(task(1))['outcome'] == 'dispatch_off' and autos() == []


def test_slot_idempotency_never_duplicates(box):
    enable(portals=['no'], min_interval_seconds=3600)
    now = 1_900_000_000
    first = auto.run(rows_fn=queue(task(1)), destination_ok=lambda t: True, now=now)
    assert first['created'] == 1
    jobs_before = autos()
    again()
    # same slot, unit still queued -> blocked by the active-delivery reservation, never a second job
    second = auto.run(rows_fn=queue(task(1)), destination_ok=lambda t: True, now=now + 5)
    assert second['created'] == 0 and len(autos()) == len(jobs_before)
    # the deterministic key replays even if the reservation were gone: same receipt, no new row
    policy = {'id': 'auto', 'version': 1, 'slot': first['slot']}
    receipt = jobs.create_delivery({'domain': 'domestic', 'subject': {'kind': 'offer', 'id': 1}, 'portal': 'no', 'action': 'add',
                                    'package': {'mode': 'ensure_current'}}, actor='policy:auto',
                                   idempotency_key=auto._key({'policy_id': 'auto', 'policy_version': 1}, first['slot'],
                                                             ('domestic', 'offer', 1, 'no'), 'add'),
                                   dispatch_enabled=True, source='automation', policy=policy)
    assert receipt.replayed is True and len(autos()) == 1


def test_lock_busy_is_retried_without_recording_a_run(box):
    from InvestmentManager.integrator.input_consistency import LockBusy
    enable(portals=['no'])

    def busy(**kw):
        raise LockBusy('busy')
    assert auto.run(rows_fn=busy, destination_ok=lambda t: True)['outcome'] == 'lock_busy'
    assert auto.read_state()['runs'] == [] and go(task(1))['outcome'] == 'created'


def test_queue_failure_is_recorded_and_creates_nothing(box):
    enable(portals=['no'])

    def broken(**kw):
        raise RuntimeError('boom')
    summary = auto.run(rows_fn=broken, destination_ok=lambda t: True)
    assert summary['outcome'] == 'error' and summary['code'] == 'queue_unavailable' and autos() == []


def test_scan_is_bounded(box):
    enable(portals=['no'], max_per_run=1)
    rows = [task(n, portal='tabelaofert') for n in range(1, 700)]
    summary = go(*rows)
    assert summary['scanned'] == 500 and summary['truncated'] is True and summary['outcome'] == 'nothing_to_do'


# ------------------------------------------------------------------ job-store invariants
def test_automation_source_needs_a_policy_and_an_automation_actor(box):
    intent = {'domain': 'domestic', 'subject': {'kind': 'offer', 'id': 1}, 'portal': 'no', 'action': 'add', 'package': {'mode': 'ensure_current'}}
    key = uuid.uuid4().hex
    with pytest.raises(jobs.AutomationNotSupported):
        jobs.create_delivery(intent, actor='policy:auto', idempotency_key=key, dispatch_enabled=True, source='automation')
    with pytest.raises(jobs.AutomationNotSupported):
        jobs.create_delivery(intent, actor=ACTOR, idempotency_key=key, dispatch_enabled=True, policy={'id': 'auto', 'version': 1, 'slot': 's'})
    with pytest.raises(jobs.InvalidRequest):                                   # manual job with a policy actor
        jobs.create_delivery(intent, actor='policy:auto', idempotency_key=key, dispatch_enabled=True)
    for policy in ({'id': 'other', 'version': 1, 'slot': 's'}, {'id': 'auto', 'version': 0, 'slot': 's'},
                   {'id': 'auto', 'version': 1, 'slot': ''}, {'id': 'auto', 'version': 1}):
        with pytest.raises(jobs.InvalidRequest):
            jobs.create_delivery(intent, actor='policy:auto', idempotency_key=key, dispatch_enabled=True, source='automation', policy=policy)
    with pytest.raises(jobs.InvalidRequest):                                   # automation never creates ACK-only jobs
        jobs.create_ack_recovery({'domain': 'domestic', 'attempt_id': 'a' * 32, 'subject_kind': 'offer', 'subject_id': 1, 'portal': 'no',
                                  'action': 'add', 'package_id': 'b' * 32, 'binding_sha256': 'c' * 64, 'attempt_anchor_id': 1},
                                 actor='policy:auto', idempotency_key=key)
    assert _rows('SELECT COUNT(*) AS n FROM export_jobs')[0]['n'] == 0


def test_dispatch_pause_still_blocks_automation_creation_in_the_store(box):
    intent = {'domain': 'domestic', 'subject': {'kind': 'offer', 'id': 1}, 'portal': 'no', 'action': 'add', 'package': {'mode': 'ensure_current'}}
    with pytest.raises(jobs.DispatchPaused):
        jobs.create_delivery(intent, actor='policy:auto', idempotency_key=uuid.uuid4().hex, dispatch_enabled=False,
                             source='automation', policy={'id': 'auto', 'version': 1, 'slot': 's'})


# ------------------------------------------------------------------ executor integration
def test_automation_jobs_run_through_the_same_executor_one_per_tick(box, stub, monkeypatch):
    enable(portals=['no'], max_per_run=3)
    monkeypatch.setattr('InvestmentManager.integrator.sync_tasks.list_task_rows', queue(task(1), task(2), task(3)))
    monkeypatch.setattr(auto, '_destination_ok', lambda t: True)
    first = runner.tick_one(env=None)
    assert first['automation']['created'] == 3 and first['outcome'] == 'executed'
    assert [call[2] for call in stub] == ['automation'] and len(stub) == 1             # FIFO, one execution per tick
    for _ in range(2):
        again()                                                                          # nothing new, only drain the queue
        runner.tick_one(env=None)
    assert len(stub) == 3 and {r['state'] for r in autos()} == {'completed'}


def test_disabling_cancels_queued_automation_jobs_but_not_recovery_or_ack_only(box, stub, monkeypatch):
    enable(portals=['no'], max_per_run=2)
    go(task(1), task(2))
    ack = jobs.create_ack_recovery({'domain': 'domestic', 'attempt_id': 'a' * 32, 'subject_kind': 'offer', 'subject_id': 30,
                                    'portal': 'no', 'action': 'add', 'package_id': 'b' * 32, 'binding_sha256': 'c' * 64,
                                    'attempt_anchor_id': 30}, actor=ACTOR, idempotency_key=uuid.uuid4().hex)
    orphan_manual = jobs.create_delivery({'domain': 'domestic', 'subject': {'kind': 'offer', 'id': 50}, 'portal': 'no', 'action': 'add',
                                          'package': {'mode': 'ensure_current'}}, actor=ACTOR, idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)
    auto.disable(changed_by='test')
    result = runner.tick_one(env=None)
    assert result['automation']['cancelled_queued'] == 2
    assert result['executed']['kind'] == 'ack_only' and jobs.get_job(ack.job_id)['state'] == 'completed'
    assert {r['state'] for r in autos()} == {'cancelled'}
    assert jobs.get_job(orphan_manual.job_id)['state'] == 'queued'
    assert 'automation' not in runner.tick_one(env=None)                                 # nothing left to report


def test_a_failing_automation_never_breaks_the_tick(box, stub, monkeypatch):
    enable(portals=['no'])
    monkeypatch.setattr(auto, 'run', lambda: (_ for _ in ()).throw(RuntimeError('boom')))
    jobs.create_delivery({'domain': 'domestic', 'subject': {'kind': 'offer', 'id': 5}, 'portal': 'no', 'action': 'add',
                          'package': {'mode': 'ensure_current'}}, actor=ACTOR, idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)
    result = runner.tick_one(env=None)
    assert result['automation'] == {'outcome': 'error', 'code': 'automation_failed', 'error_type': 'RuntimeError'}
    assert result['outcome'] == 'executed' and len(stub) == 1


def test_automation_does_not_run_in_recovery_only_mode(box, stub, monkeypatch):
    enable(portals=['no'])
    monkeypatch.setattr(auto, 'run', lambda: pytest.fail('automation must not run'))
    assert runner.tick_one(mode='recovery_and_ack_only', env=None)['outcome'] == 'idle'


def test_automation_has_no_transport_of_its_own():
    import inspect
    source = inspect.getsource(auto)
    for forbidden in ('ftplib', 'socket', 'subprocess', 'portal_transport', 'package_delivery', 'start_qualified_transport', 'start_gated_transport', 'export_start'):
        assert forbidden not in source


# ------------------------------------------------------------------ CLI
def test_cli_enable_status_disable(box, capsys):
    assert runner.main(['automation-enable']) == 1                                      # portals are mandatory
    assert json.loads(capsys.readouterr().out)['code'] == 'invalid_automation_config'
    assert runner.main(['automation-enable', '--portals', 'no,domiporta', '--categories', 'new', '--max-per-run', '1']) == 0
    out = json.loads(capsys.readouterr().out)
    assert out['enabled'] is True and out['config']['portals'] == ['no', 'domiporta'] and out['config']['max_per_run'] == 1
    assert runner.main(['automation-status']) == 0 and json.loads(capsys.readouterr().out)['enabled'] is True
    assert runner.main(['automation-enable', '--portals', 'nope']) == 1
    capsys.readouterr()
    assert runner.main(['automation-disable']) == 0 and json.loads(capsys.readouterr().out)['enabled'] is False
    assert runner.main(['pause', '--automation']) == 1                                  # the legacy flag stays unsupported
    assert json.loads(capsys.readouterr().out)['code'] == 'automation_not_supported'
