"""Stage 5B-1: deploying the new code must not start any export by itself.

The production cron calls `scheduled_jobs tick` every minute. These tests model the states the host goes through and assert,
for each, that no job is created, no job is claimed/executed and NO transport (FTP) is reached unless BOTH explicit,
file-backed switches are set by an operator. Every state lives in files/DB, so a restarted process sees the same state.
"""
from contextlib import closing
import hashlib
import json
import sqlite3
import subprocess
import sys
import uuid
from pathlib import Path

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 InvestmentManager.integrator import portal_transport
from tests.investmentmanager import qualification_support as support

REPO = Path(__file__).resolve().parents[2]
USER = 'user:7'


class Reached(AssertionError):
    pass


@pytest.fixture
def host(tmp_path, monkeypatch):
    """A 'production-like' DATA_DIR: the existing databases only, NO export tables, NO control file."""
    root = tmp_path / 'InvestmentData'
    root.mkdir()
    monkeypatch.setenv('DATA_DIR', str(root))
    support.init_root(root)
    calls = []

    def transport(*args, **kwargs):
        calls.append(args)
        raise Reached('a transport (FTP) call was reached')
    monkeypatch.setattr(portal_transport, 'upload_portal_zip', transport)
    import ftplib
    monkeypatch.setattr(ftplib.FTP, 'connect', lambda *a, **k: (_ for _ in ()).throw(Reached('ftplib connect')))
    import socket
    monkeypatch.setattr(socket.socket, 'connect', lambda *a, **k: (_ for _ in ()).throw(Reached('socket connect')))
    return root


def logical_hash(root):
    result = {}
    for path in sorted((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 tree(root):
    return sorted(p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file() and not p.name.endswith(('-wal', '-shm')))


def make_job(subject=10, portal='no'):
    return jobs.create_delivery({'domain': 'domestic', 'subject': {'kind': 'offer', 'id': subject}, 'portal': portal, 'action': 'add',
                                 'package': {'mode': 'ensure_current'}}, actor=USER, idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)


def count(sql):
    with jobs._reader(jobs.WORKER_TIMEOUT) as conn:
        return conn.execute(sql).fetchone()[0]


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


def queue_rows(monkeypatch, *subjects):
    from InvestmentManager.integrator import sync_tasks
    monkeypatch.setattr(sync_tasks, 'list_task_rows', lambda **kw: {'items': [task(s) for s in subjects], 'total': len(subjects)})
    monkeypatch.setattr(auto, '_destination_ok', lambda t: True)


# ---------------------------------------------------------------- state 1: new code, no schema, no control file
def test_state1_code_deployed_without_schema_is_completely_inert(host):
    before_db, before_files = logical_hash(host), tree(host)
    assert runner.tick_one() is None                                              # exports idle: the historical tick response is unchanged
    assert scheduled_jobs._tick_exports({'outcome': 'not_due'}) is None
    assert scheduled_jobs._tick_exports({'outcome': 'scheduler_error'}) is None   # even the recovery-only mode does nothing without a store
    assert logical_hash(host) == before_db                                        # the tick never creates the schema
    assert set(tree(host)) - set(before_files) <= {'scheduler/runner.lock'}
    assert control.read()['status'] == 'missing' and control.dispatch_enabled() is False
    assert auto.read_config()['enabled'] is False


def test_state1_http_cannot_create_anything_without_schema(host):
    with pytest.raises(jobs.JobError):
        jobs.create_delivery({'domain': 'domestic', 'subject': {'kind': 'offer', 'id': 10}, 'portal': 'no', 'action': 'add',
                              'package': {'mode': 'ensure_current'}}, actor=USER, idempotency_key=uuid.uuid4().hex, dispatch_enabled=False)


# ---------------------------------------------------------------- state 2: schema created (init-schema) but dispatch never enabled
def test_state2_schema_present_dispatch_missing_nothing_runs(host, monkeypatch):
    assert jobs.init_schema(backup=False) == 'created'
    control.set_dispatch(True, changed_by='setup')
    job = make_job()                                      # an operator queued a job while sending was enabled ...
    control.set_dispatch(False, changed_by='ops')          # ... then paused (or the control file is later lost/corrupted)
    for _ in range(3):
        result = runner.tick_one()
        assert result['outcome'] == 'idle' and result['dispatch_enabled'] is False and 'executed' not in result
    state = jobs.get_job(job.job_id)
    assert state['state'] == 'queued' and state['phase'] == 'accepted'                # never claimed
    (host / 'scheduler' / control.NAME).unlink()                                      # control file missing == OFF
    assert runner.tick_one()['dispatch_enabled'] is False and jobs.get_job(job.job_id)['state'] == 'queued'
    (host / 'scheduler' / control.NAME).write_text('{broken', encoding='utf-8')       # corrupt == fail closed
    result = runner.tick_one()
    assert result['dispatch_enabled'] is None and 'executed' not in result and jobs.get_job(job.job_id)['state'] == 'queued'


def test_state2_automation_cannot_create_jobs_without_config(host, monkeypatch):
    jobs.init_schema(backup=False)
    control.set_dispatch(True, changed_by='setup')       # sending enabled, automation never configured
    queue_rows(monkeypatch, 1, 2, 3)
    for _ in range(3):
        result = runner.tick_one()
        assert 'automation' not in result and 'executed' not in result
    assert count('SELECT COUNT(*) FROM export_jobs') == 0


def test_state2_automation_enabled_but_dispatch_off_creates_nothing(host, monkeypatch):
    jobs.init_schema(backup=False)
    auto.enable(portals=['no'], changed_by='ops')                                 # automation switch ON, dispatch switch OFF/missing
    queue_rows(monkeypatch, 1, 2, 3)
    for _ in range(3):
        result = runner.tick_one()
        assert 'automation' not in result and 'executed' not in result
    assert count('SELECT COUNT(*) FROM export_jobs') == 0


def test_activation_needs_both_switches_and_even_then_transport_needs_the_atomic_start(host, monkeypatch):
    jobs.init_schema(backup=False)
    queue_rows(monkeypatch, 1)
    auto.enable(portals=['no'], changed_by='ops')
    control.set_dispatch(True, changed_by='ops')          # BOTH explicit switches
    result = runner.tick_one()
    assert result['automation']['created'] == 1           # a queued job exists ...
    # ... and the executor reaches the job; the environment has no FTP credentials/packages, so START never grants a send:
    assert count("SELECT COUNT(*) FROM export_jobs WHERE state='queued' OR state='blocked' OR state='failed' OR state='running'") == 1


def test_a_job_claimed_before_a_pause_is_still_refused_at_start(host, monkeypatch):
    """Dispatch is re-read inside the atomic START transaction: a pause between claim and START prevents the send."""
    jobs.init_schema(backup=False)
    control.set_dispatch(True, changed_by='ops')
    make_job()
    control.set_dispatch(False, changed_by='ops')
    assert runner.tick_one()['outcome'] == 'idle'
    source = Path(REPO / 'InvestmentManager/integrator/export_start.py').read_text(encoding='utf-8')
    assert 'dispatch_paused' in source and 'export_control.dispatch_enabled()' in source       # the START gate reads the file itself


# ---------------------------------------------------------------- recovery and ACK-only never reach FTP
def test_recovery_and_ack_only_run_while_paused_without_any_transport(host, monkeypatch):
    jobs.init_schema(backup=False)
    control.set_dispatch(True, changed_by='ops')
    ack = jobs.create_ack_recovery({'domain': 'domestic', 'attempt_id': 'a' * 32, 'subject_kind': 'offer', 'subject_id': 10, 'portal': 'no',
                                    'action': 'add', 'package_id': 'b' * 32, 'binding_sha256': 'c' * 64, 'attempt_anchor_id': 10},
                                   actor=USER, idempotency_key=uuid.uuid4().hex)
    control.set_dispatch(False, changed_by='ops')
    result = runner.tick_one()                            # ACK-only is allowed while paused, never sends
    assert result['outcome'] == 'executed' and result['executed']['kind'] == 'ack_only'
    assert jobs.get_job(ack.job_id)['state'] in ('blocked', 'needs_review', 'completed')          # attempt absent: blocked, no FTP


def test_static_audit_only_the_job_executor_reaches_the_transport():
    import re
    callers = []
    for path in (REPO / 'InvestmentManager').rglob('*.py'):
        text = path.read_text(encoding='utf-8')
        if re.search(r'\bupload_portal_zip\(', text) and 'def upload_portal_zip' not in text:
            callers.append(str(path.relative_to(REPO)).replace('\\', '/'))
    assert 'InvestmentManager/integrator/package_delivery.py' in callers
    runners = [str(p.relative_to(REPO)).replace('\\', '/') for p in (REPO / 'InvestmentManager').rglob('*.py')
               if re.search(r'execute_delivery\(|execute_ack_only\(', p.read_text(encoding='utf-8')) and 'def execute_' not in p.read_text(encoding='utf-8')]
    assert runners == ['InvestmentManager/integrator/export_job_runner.py']                        # only the executor starts deliveries
    # the legacy engine uploader exists in the tree but nothing outside the engine package calls it
    outside = [c for c in callers if not c.startswith('InvestmentManager/export_engine/') and not c.endswith('package_delivery.py')]
    assert outside == []


# ---------------------------------------------------------------- state survives a restart of the process
def test_state_survives_a_process_restart(host):
    jobs.init_schema(backup=False)
    control.set_dispatch(False, changed_by='ops')
    out = subprocess.run([sys.executable, '-B', '-m', 'InvestmentManager.integrator.export_job_runner', 'status'], cwd=REPO,   # inherits DATA_DIR
                         capture_output=True, text=True, encoding='utf-8', timeout=120)
    assert out.returncode == 0, out.stderr[-500:]
    status = json.loads(out.stdout.strip().splitlines()[-1])
    assert status['control']['dispatch_enabled'] is False and status['schema'] == 'ready'
