"""Completed operation guidance must remain factual, inert and engine-driven."""
import copy
import hashlib
import json
from pathlib import Path
import subprocess
import sys
from pycforge_sdk import SDK
from pycforge_sdk.handoff import packaged, registered
from pycforge_sdk.project import Project


def test_default_sdk_supports_local_manual_and_guidance_without_io(project, tmp_path, monkeypatch):
    monkeypatch.setattr(Path, 'home', classmethod(lambda cls: tmp_path/'default-home'))
    client = SDK()
    assert client._connection.python == sys.executable
    assert client._connection.cache == tmp_path/'default-home/.pycforge-sdk/cache'
    monkeypatch.setattr(client._connection, 'discover', lambda: (_ for _ in ()).throw(AssertionError('Unexpected engine discovery')))
    assert client.manual(topic='api').ok and client.authoring_guide(project).ok
    assert not (tmp_path/'default-home').exists()
    assert not any(n=='PySide6' or n=='pycforge' or n.startswith('pycforge.') for n in sys.modules)


def test_build_handoff_matches_verified_inputs_and_never_registers(sdk, project, tmp_path):
    before = Project.load(project)
    assert sdk.verify(project, compiler='gcc').ok
    inspection = sdk.inspect(project).data['inspection']['extension']
    destination = tmp_path/'handoff.pcfplugin'
    result = sdk.build(project, destination); assert result.ok, result.to_dict()
    value = result.data['handoff']
    assert value['extension'] == inspection
    assert value['artifact']['sha256'] == hashlib.sha256(destination.read_bytes()).hexdigest()
    assert value['artifact']['file'] == str(destination)
    assert value['import_statement'] == '*import example as extension'
    assert value['registration'] == {'state':'not-requested', 'engine_result':None}
    assert result.data['registered'] is False
    case = next(c for c in before.document['cases'] if c['name']==value['example']['name'])
    assert case['expect']['kind'] == 'run'
    assert value['example']['source'] == dict(before.sources)[case['file']].decode()
    assert all(value['example'][key]==case['expect'][key] for key in ('stdout','stderr','exit_code'))
    assert Project.load(project).sha256 == before.sha256
    assert not (tmp_path/'registry.json').exists()
    original_bytes = destination.read_bytes()
    document = sdk.open_project(project).data
    document['document']['metadata']['description'] = 'Changed after packaging'
    assert sdk.save_project(project, document['document'], expected_sha256=document['project_sha256']).ok
    refused = sdk.build(project, destination)
    assert not refused.ok and 'handoff' not in refused.data and destination.read_bytes()==original_bytes


def test_cli_and_python_handoff_agree_and_registration_reports_actual_engine_result(sdk, project, tmp_path, engine_python):
    assert sdk.verify(project, compiler='gcc').ok
    destination = tmp_path/'client.pcfplugin'
    direct = sdk.build(project, destination)
    args = [sys.executable, '-m', 'pycforge_sdk', '--engine-python', str(engine_python), '--cache', str(tmp_path/'cli-cache')]
    command = ['build', str(project), '--output', str(destination)]
    result = subprocess.run([*args, '--json', *command], capture_output=True, text=True, timeout=30)
    assert result.returncode == 0, result.stderr
    assert json.loads(result.stdout) == direct.to_dict()
    text = subprocess.run([*args, *command], capture_output=True, text=True, timeout=30)
    assert text.returncode == 0 and '*import example as extension' in text.stdout
    assert 'Registration is a separate explicit action' in text.stdout and 'Verified Help example:' in text.stdout
    store = tmp_path/'registry.json'
    reply = sdk.register(destination, store=store); assert reply.ok, reply.to_dict()
    value = reply.data['handoff']
    assert value['registration']['engine_result'] == reply.data['registration']
    assert value['artifact']['sha256'] == direct.data['sha256']
    assert value['stage']=='registered' and value['example'] is None
    assert value['import_statement']=='*import example as extension'
    cli = subprocess.run([*args, '--json', 'register', str(destination), '--store', str(store)], capture_output=True, text=True, timeout=30)
    assert cli.returncode==0 and json.loads(cli.stdout)==reply.to_dict()


def test_rejected_registration_never_advertises_usable_import(sdk, tmp_path):
    package = tmp_path/'invalid.pcfplugin'; package.write_bytes(b'not an import package')
    reply = sdk.register(package, store=tmp_path/'registry.json')
    assert not reply.ok, reply.to_dict()
    value = reply.data['handoff']
    assert value['stage']=='registration-failed' and value['import_statement'] is None
    assert value['registration']['engine_result']==reply.data['registration']
    assert package.read_bytes()==b'not an import package'


def test_handoff_preserves_additive_engine_data_and_does_not_guess_a_missing_namespace():
    data = {'package':'future.pcfplugin','sha256':'a','bytes':1,'package_format':'future.format/9',
            'project_sha256':'b','evidence_sha256':'c'}
    extension = {'version':'next','future':{'choices':[True,1,1.0]},'namespace':'future_namespace'}
    before = copy.deepcopy(extension)
    value = packaged(data, extension, {'engine_version':'future'}, None)
    assert value['extension']==before and value['artifact']['format']=='future.format/9'
    value['extension']['future']['choices'].append(None); assert extension==before
    extension.pop('namespace')
    assert packaged(data, extension, {}, None)['import_statement'] is None
    row = {'status':'FutureStatus','message':'Engine explanation','future':{'keep':True}}
    report = registered(row, {})
    assert report['import_statement'] is None and report['registration']['engine_result']==row
