"""Structured values use the public engine workflow and inert four-field forms."""
import io
import json
import zipfile
import pytest
from pycforge_sdk import SDK
from pycforge_sdk.package_metadata import archive_format
from pycforge_sdk.results import SDKError


@pytest.mark.parametrize('template,namespace', [('json-values','json'),('value-starter','records')])
def test_value_packages_verify_build_register_and_reject_stale_help(sdk,tmp_path,template,namespace):
    folder=tmp_path/template
    result=sdk.create_project(folder,author='Independent value qualification',template=template)
    assert result.ok,result.to_dict()
    assert sdk.scan(folder).ok
    blocked=sdk.build(folder,tmp_path/'unverified.pcfplugin')
    assert not blocked.ok and not (tmp_path/'unverified.pcfplugin').exists()
    checked=sdk.verify(folder,compiler='gcc')
    assert checked.ok,checked.to_dict()
    assert all(case['passed'] for case in checked.data['report']['cases'])
    first,second=tmp_path/'first.pcfplugin',tmp_path/'second.pcfplugin'
    built=sdk.build(folder,first)
    assert built.ok,built.to_dict()
    assert built.data['package_format']=='pycforge.value-package/0.1'
    assert sdk.build(folder,second).ok and first.read_bytes()==second.read_bytes()
    with zipfile.ZipFile(first) as archive:
        manifest=json.loads(archive.read('manifest.json'))
        assert manifest['profile']=='crucible.json-values/0.1'
        assert manifest['extension_api']=='0.4'
        assert manifest['namespace']==namespace
        assert set(archive.namelist())=={'manifest.json','conversion.json','documentation.json'}
    registration=sdk.register(first,store=tmp_path/'registry.json')
    assert registration.ok,registration.to_dict()
    previous=first.read_bytes()
    path=folder/'project.json';document=json.loads(path.read_bytes())
    document['documentation']['overview']+=' Changed after verification.'
    path.write_text(json.dumps(document))
    stale=sdk.build(folder,first)
    assert not stale.ok and stale.diagnostics[0]['code']=='SDK_STALE_EVIDENCE'
    assert first.read_bytes()==previous


def test_value_reference_and_forms_are_available_offline(sdk,tmp_path):
    cards=sdk.templates();assert cards.ok,cards.to_dict()
    assert {'json-values','value-starter'} <= {c['id'] for c in cards.data['templates']}
    description=sdk.describe('ValueFunction');assert description.ok,description.to_dict()
    assert [p['name'] for p in description.data['method']['parameters']]==['operation_id','export','operation','summary']
    workbench=sdk.workbench();assert workbench.ok
    form=next(p for p in workbench.data['workbench']['profiles'] if p['declaration_schema']=='crucible.value-declaration/0.1')
    assert [f['name'] for f in form['function_fields']]==['operation_id','export','operation','summary']
    client=SDK(engine_python=tmp_path/'missing-python',cache=tmp_path/'cache')
    assert client.connect().status=='incomplete'
    offline=client.describe('ValueFunction')
    assert offline.data['method']==description.data['method']
    assert offline.data['connection']['state']=='offline'
    assert not offline.data['connection']['execution_available']
    assert client.workbench().data['workbench']==workbench.data['workbench']


def test_package_report_accepts_future_engine_format_without_family_dispatch():
    buffer=io.BytesIO()
    with zipfile.ZipFile(buffer,'w') as archive:
        archive.writestr('manifest.json',json.dumps({'format':'example.future-package/3.1'}))
    assert archive_format(buffer.getvalue())=='example.future-package/3.1'


@pytest.mark.parametrize('manifest',[{},[],{'format':None},{'format':''},{'format':42},{'format':'x'*201}])
def test_invalid_engine_package_identity_is_a_structured_failure(manifest):
    buffer=io.BytesIO()
    with zipfile.ZipFile(buffer,'w') as archive:
        archive.writestr('manifest.json',json.dumps(manifest))
    with pytest.raises(SDKError) as failure:archive_format(buffer.getvalue())
    assert failure.value.code=='SDK_ENGINE_ERROR'


def test_value_choices_are_discoverable_through_methods_and_describe(sdk):
    choices = sdk.methods().data['value_operations']
    assert {c['id'] for c in choices} >= {'json-loads', 'json-dumps'}
    assert sdk.describe('ValueFunction').data['value_operations'] == choices
