"""A real selected-engine-only addition, with the SDK source held unchanged."""
from pathlib import Path
import hashlib
import json
import os
import shutil
import subprocess
import sys
from pycforge_sdk import SDK


def invoke(argv, **kwargs):
    result=subprocess.run([str(a) for a in argv],capture_output=True,text=True,timeout=60,**kwargs)
    assert result.returncode==0,(result.stdout,result.stderr)
    return result.stdout


def test_unchanged_sdk_accepts_new_engine_help_template_and_pack_without_sdk_in_engine(tmp_path,engine_python):
    import pycforge_sdk
    sdk_root=Path(pycforge_sdk.__file__).parent
    def sdk_hashes():
        return {str(p.relative_to(sdk_root)):hashlib.sha256(p.read_bytes()).hexdigest()
                for p in sdk_root.rglob('*') if p.is_file() and '__pycache__' not in p.parts}
    before=sdk_hashes()
    source=Path(invoke([engine_python,'-I','-c','import pathlib,pycforge;print(pathlib.Path(pycforge.__file__).parent)']).strip())
    package=tmp_path/'engine'/'pycforge'
    shutil.copytree(source,package,ignore=shutil.ignore_patterns('__pycache__'))
    environment=tmp_path/'engine-env'
    invoke([sys.executable,'-m','venv','--without-pip',environment])
    python=environment/('Scripts/python.exe' if os.name=='nt' else 'bin/python')
    purelib=Path(invoke([python,'-I','-c','import sysconfig;print(sysconfig.get_paths()["purelib"])']).strip())
    (purelib/'engine.pth').write_text(str(package.parent)+'\n')
    assert invoke([python,'-I','-c','import importlib.util;print(importlib.util.find_spec("pycforge_sdk"))']).strip()=='None'
    client=SDK(engine_python=python,cache=tmp_path/'cache')
    assert client.connect().ok
    assert client.workbench().data['source'] == 'engine'
    first=tmp_path/'old-project'
    assert client.create_project(first,author='Compatibility fixture').ok
    assert client.verify(first,compiler='gcc').ok
    # Synthetic engine B: add one public method and one compatible template.
    # This fixture is not a published PyCForge release.
    authoring=package/'crucible/authoring.py'
    authoring.write_text(authoring.read_text()+'''\ndef _explain(self) -> dict:\n    """Describe the same scalar candidate using the new public method."""\n    return self.inspect()\nScalarAuthoring.explain = _explain\n''')
    authoring.write_text(authoring.read_text()+'''
_previous_extension_init = ExtensionAuthoring.__init__
def _future_extension_init(self, declaration: dict):
    import copy
    if declaration.get('schema') == 'example.future-scalar/1.0':
        declaration = copy.deepcopy(declaration)
        declaration['schema'] = 'crucible.scalar-declaration/0.1'
        for function in declaration['functions']:
            if function.pop('units', None) != 'dimensionless':
                raise ValueError('The future profile requires dimensionless units.')
    _previous_extension_init(self, declaration)
ExtensionAuthoring.__init__ = _future_extension_init
''')
    reference=package/'crucible/authoring_reference.py'
    text=reference.read_text().replace('def authoring_reference() -> dict:', 'def _original_reference() -> dict:')
    text+='''\n\ndef authoring_reference() -> dict:
    """Read the compatible expanded engine reference."""
    data = _original_reference()
    entry = copy.deepcopy(next(e for e in data['entries'] if e['id'].endswith('.inspect')))
    entry.update(id='pycforge.crucible.ScalarAuthoring.explain', public_path='pycforge.crucible.ScalarAuthoring.explain', title='Explain the candidate', summary='New engine-owned method explanation.')
    data['entries'].append(entry)
    template = copy.deepcopy(data['templates'][0])
    template.update(id='scalar-absolute', title='Absolute value extension')
    template['declaration'].update(package_id='org.example.absolute', namespace='absolute')
    template['declaration']['schema'] = 'example.future-scalar/1.0'
    data['declaration_schemas'].append('example.future-scalar/1.0')
    template['declaration']['functions'][0].update(operation_id='absolute.fabs', export='fabs', native_symbol='fabs', summary='Absolute value')
    template['documentation']['functions']['fabs'] = template['documentation']['functions'].pop('cbrt')
    template['documentation']['functions']['fabs']['returns'] = 'Floating absolute value.'
    template['documentation']['functions']['fabs']['details'] = 'Magnitude of a scalar number.'
    for case in template['cases']:
        case['source'] = case['source'].replace('*import example', '*import absolute').replace('cbrt', 'fabs')
        if case['expect']['kind'] == 'run':
            case['expect']['stdout'] = '8.0\\n8.0\\n0.0\\n'
    while len(template['cases']) < 65:
        extra = copy.deepcopy(template['cases'][-1])
        extra['name'] = 'future_rejection_' + str(len(template['cases']))
        template['cases'].append(extra)
    data['templates'].append(template)
    return data
'''
    reference.write_text(text)
    workbench=package/'crucible/sdk_workbench.py'
    workbench.write_text(workbench.read_text()+'''
_original_workbench = workbench_reference
def workbench_reference():
    value = _original_workbench()
    profile = next(p for p in value['profiles'] if p['declaration_schema'] == 'example.future-scalar/1.0')
    profile['title'] = 'Future engine-owned scalar profile'
    profile['function_fields'].append(field('units', 'Units from the engine', 'Engine-owned dimension annotation.'))
    return value
''')
    guide=package/'crucible/landscape/sdk-help.html'
    guide.write_text(guide.read_text().replace('</body>','<h2>Future engine guide</h2><p>New Help without an SDK update.</p></body>'))
    (package/'_version.py').write_text('__version__ = "1.3.71"\n')
    # Clear copied bytecode so timestamp resolution cannot hide the fixture edit.
    for cached in package.rglob('__pycache__'):shutil.rmtree(cached)
    invoke([python,'-I','-c','from pathlib import Path;from pycforge.crucible import sdk_api;folder=Path(sdk_api.__file__).with_name("landscape");[(folder/name).write_bytes(data) for name,data in sdk_api.exported_files().items()]'])
    stale=client.inspect(first)
    assert stale.status=='incomplete' and stale.diagnostics[0]['code']=='SDK_STALE_ENGINE'
    assert client.connect().ok
    expanded=client.workbench().data
    profile=next(p for p in expanded['workbench']['profiles'] if p['declaration_schema']=='example.future-scalar/1.0')
    assert profile['function_fields'][-1]['name']=='units'
    assert 'Future engine guide' in expanded['documents'][0]['html']
    assert client.describe('ScalarAuthoring.explain').data['method']['summary']=='New engine-owned method explanation.'
    assert not client.build(first,tmp_path/'stale.pcfplugin').ok
    second=tmp_path/'new-project'
    assert client.create_project(second,author='Compatibility fixture',template='scalar-absolute').ok
    # A newly advertised field can be absent from a project. Every client must
    # expose it without silently inserting a guessed value.
    fields=client.authoring_fields(second,function='fabs');assert fields.ok,fields.to_dict()
    assert fields.data['authoring_fields']['fields'][-1]['definition']['name']=='units'
    assert fields.data['authoring_fields']['fields'][-1]['present'] is False
    cli=json.loads(invoke([sys.executable,'-m','pycforge_sdk','--json','--engine-python',python,
                          '--cache',tmp_path/'cli-cache','fields',second,'--function','fabs']))
    assert cli==fields.to_dict()
    opened=client.open_project(second).data
    opened['document']['declaration']['functions'][0]['units']='dimensionless'
    assert client.save_project(second,opened['document'],expected_sha256=opened['project_sha256']).ok
    verified=client.verify(second,compiler='gcc');assert verified.ok,verified.to_dict()
    assert len(verified.data['report']['cases'])==65
    output=tmp_path/'absolute.pcfplugin'
    assert client.build(second,output).ok
    registry=tmp_path/'registry.json'
    assert client.register(output,store=registry).ok
    # Publish the verified independent package as another bundled default in
    # this synthetic engine only; the client's import/Help lists are unchanged code.
    shutil.copyfile(output,package/'extensions/absolute.pcfplugin')
    registration=package/'crucible/import_registry.py'
    registration.write_text(registration.read_text()+"\nBUNDLED_IMPORTS = BUNDLED_IMPORTS + ('absolute',)\n")
    for cached in package.rglob('__pycache__'):shutil.rmtree(cached)
    invoke([python,'-I','-c','from pathlib import Path;from pycforge.crucible import sdk_api;folder=Path(sdk_api.__file__).with_name("landscape");[(folder/name).write_bytes(data) for name,data in sdk_api.exported_files().items()]'])
    assert client.connect().ok
    assert 'absolute' in {row['namespace'] for row in client.workbench().data['workbench']['imports']}
    assert any(doc['id']=='import:absolute' for doc in client.workbench().data['documents'])
    # Production conversion consumes the registered package with SDK absent.
    script='''import importlib.util,os,pathlib,sys
assert importlib.util.find_spec('pycforge_sdk') is None
os.environ['PYCFORGE_CONVERSION_IMPORTS']=sys.argv[1]
from pycforge import PythonToCConverter,ConversionRequest
from pycforge.converter.runtime_values.service import request_options
result=PythonToCConverter().convert(ConversionRequest.from_source('*import absolute as a\\ndef main():\\n    print(a.fabs(-3.5))\\n    return 0\\n',**request_options()))
assert result.generated_c, result.diagnostics
pathlib.Path(sys.argv[2]).write_text(result.generated_c)
'''
    c=tmp_path/'consumer.c';exe=tmp_path/'consumer'
    invoke([python,'-I','-c',script,registry,c])
    invoke(['gcc','-std=c11','-O1','-DPYCF_RUNTIME_MAIN',c,'-lm','-o',exe])
    assert invoke([exe])=='3.5\n'
    good_pointer=(client._connection.cache/'current.json').read_bytes()
    workbench.write_text(workbench.read_text()+'''
_compatible_workbench = workbench_reference
def workbench_reference():
    value = _compatible_workbench()
    value['schema'] = 'pycforge.sdk-workbench/2.0'
    return value
''')
    for cached in package.rglob('__pycache__'):shutil.rmtree(cached)
    invoke([python,'-I','-c','from pathlib import Path;from pycforge.crucible import sdk_api;folder=Path(sdk_api.__file__).with_name("landscape");[(folder/name).write_bytes(data) for name,data in sdk_api.exported_files().items()]'])
    refused=client.connect()
    assert refused.data['state']=='offline' and not refused.data['execution_available']
    assert (client._connection.cache/'current.json').read_bytes()==good_pointer
    assert client.workbench().data['workbench']['schema']=='pycforge.sdk-workbench/1.0'
    assert sdk_hashes()==before
