"""SDK coverage gates, version migration and genuine external extension use."""
import json
import os
from pathlib import Path
import subprocess
import pytest
from pycforge_sdk import SDK
from pycforge_sdk.catalogue import signature_compatible


@pytest.mark.parametrize('old,new,accepted', [
    ("(x: 'str', y=1)", "(x: 'str', y=1, errors='direct')", True),
    ("(x, *, y=1)", "(x, *, y=1, z=False)", True),
    ("(x, y=1)", "(x, y=2)", False),
    ("(x)", "(x, required)", False),
    ("(x)", "(renamed)", False),
    ("(x, /)", "(x)", False),
    ("(x, *args)", "(x, added=1, *args)", False),
    ("(x, **kwargs)", "(x, added=1, **kwargs)", False),
    ("(x) -> int", "(x) -> float", False),
    ("(x=1)", "invalid syntax", False),
])
def test_refresh_preserves_existing_call_shapes(old, new, accepted):
    assert signature_compatible(old,new) is accepted


def test_uncalled_export_cannot_receive_a_passing_sdk_build(sdk, project, tmp_path):
    path=project/'project.json'; data=json.loads(path.read_text())
    data['declaration']['functions'].append({'operation_id':'example.sqrt','export':'sqrt','native_symbol':'sqrt',
        'summary':'This newly declared export needs a fixture'})
    data['documentation']['functions']['sqrt']={'parameters':['Nonnegative argument.'], 'returns':'Square root.', 'details':'Requires its own passing fixture.', 'example':'positive-negative-zero'}
    path.write_text(json.dumps(data))
    result=sdk.verify(project,compiler='gcc')
    assert result.status=='rejected',result.to_dict()
    assert result.diagnostics[0]['code']=='SDK_INCOMPLETE_COVERAGE'
    assert result.data['report']['coverage']['missing']==['example.sqrt']
    output=tmp_path/'preserved.pcfplugin';output.write_bytes(b'previous working artifact')
    assert not sdk.build(project,output).ok
    assert output.read_bytes()==b'previous working artifact'


def test_method_cards_and_math_template_explain_extended_contracts(sdk,tmp_path):
    described=sdk.describe('ScalarFunction')
    assert described.ok,described.to_dict()
    parameters={p['name']:p for p in described.data['method']['parameters']}
    assert 'int64' in parameters['result']['choices']
    assert 'checked-libm' in parameters['errors']['choices']
    assert parameters['integer_passthrough']['description']
    project=tmp_path/'math-project'
    made=sdk.create_project(project,author='SDK test author',template='math-scalar')
    assert made.ok,made.to_dict()
    data=json.loads((project/'project.json').read_text())
    assert len(data['declaration']['functions'])==36 and len(data['cases'])==56
    assert data['metadata']['author']=='SDK test author'
    assert not (project/'.pycforge-sdk/verification.json').exists()
    assert not sdk.build(project,tmp_path/'unverified.pcfplugin').ok


def test_independent_namespace_uses_new_contracts_through_sdk(sdk,project,tmp_path,engine_python):
    path=project/'project.json';data=json.loads(path.read_text())
    data['declaration']={'schema':'crucible.scalar-declaration/0.2','package_id':'org.example.signals',
        'version':'1.0.0','namespace':'signals','constants':[], 'functions':[
            {'operation_id':'signals.angle','export':'angle','native_symbol':'sin','domain':'not-infinite-first',
             'errors':'checked-libm','summary':'Sine of an angle in radians'},
            {'operation_id':'signals.bucket','export':'bucket','native_symbol':'floor','result':'int64',
             'errors':'checked-libm','integer_passthrough':True,'summary':'Integer bucket with exact integer identity'}]}
    data['documentation']={'schema':'pycforge.extension-author-help/0.1','overview':'Signal scalar operations.',
        'usage':'Use *import signals as s in Runtime.', 'limitations':'Scalar binary64 inputs and bounded int64 results.',
        'release_notes':'Initial independently authored signals release.', 'constants':{},
        'functions':{'angle':{'parameters':['Angle in radians.'],'returns':'Sine of the angle.', 'details':'Infinite inputs are rejected.', 'example':'behavior'},
                     'bucket':{'parameters':['Value to round downward.'],'returns':'Bounded integer bucket.', 'details':'Existing integer inputs retain their value.', 'example':'behavior'}}}
    data['cases']=[
        {'name':'behavior','file':'tests/behavior.py','expect':{'kind':'run','stdout':'0.0 2 9223372036854775807\n','stderr':'','exit_code':0}},
        {'name':'arity','file':'tests/arity.py','expect':{'kind':'reject','code':'PYC4706'}}]
    (project/'tests/behavior.py').write_text('*import signals as s\ndef main():\n    print(s.angle(0), s.bucket(2.9), s.bucket(9223372036854775807))\n    return 0\n')
    (project/'tests/arity.py').write_text('*import signals as s\ndef main():\n    return s.angle()\n')
    path.write_text(json.dumps(data))
    result=sdk.verify(project,compiler='gcc')
    assert result.ok,result.to_dict()
    assert result.data['report']['coverage']['covered']==['signals.angle','signals.bucket']
    package=tmp_path/'signals.pcfplugin'
    built=sdk.build(project,package)
    assert built.ok,built.to_dict()
    store=tmp_path/'registration.json'
    registered=sdk.register(package,store=store)
    assert registered.ok,registered.to_dict()
    script='''import importlib.util,os,sys
from pathlib import Path
from pycforge import PythonToCConverter,ConversionRequest
from pycforge.converter.runtime_values.service import request_options
assert importlib.util.find_spec("pycforge_sdk") is None
os.environ["PYCFORGE_CONVERSION_IMPORTS"]=sys.argv[1]
result=PythonToCConverter().convert(ConversionRequest.from_source(Path(sys.argv[2]).read_text(),**request_options()))
assert result.generated_c and not any(d.code=="PYC4708" for d in result.diagnostics)
print("registered production conversion passed")
'''
    run=subprocess.run([str(engine_python),'-I','-c',script,str(store),str(project/'tests/behavior.py')],
                       capture_output=True,text=True,timeout=30)
    assert run.returncode==0,run.stderr
    legacy=os.environ.get('PYCFORGE_LEGACY_ENGINE')
    if not legacy:pytest.fail('Set PYCFORGE_LEGACY_ENGINE for the old-engine refusal gate.')
    old=SDK(engine_python=legacy,cache=tmp_path/'old-cache')
    refused=old.register(package,store=tmp_path/'old-registry.json')
    assert refused.status=='rejected',refused.to_dict()
    assert refused.data['registration']['status']=='Cannot use'
    assert 'SDK' in refused.data['registration']['message']


def test_legacy_catalogue_refresh_and_project_remain_usable(tmp_path,engine_python):
    legacy=os.environ.get('PYCFORGE_LEGACY_ENGINE')
    if not legacy:pytest.fail('Set PYCFORGE_LEGACY_ENGINE to installed PyCForge 1.3.61 for the migration gate.')
    cache=tmp_path/'shared-cache'
    old=SDK(engine_python=legacy,cache=cache)
    assert old.connect().ok
    project=tmp_path/'legacy-project'
    assert old.create_project(project,author='Legacy fixture').ok
    new=SDK(engine_python=engine_python,cache=cache)
    connected=new.connect()
    assert connected.ok and connected.data['execution_available'],connected.to_dict()
    assert new.inspect(project).ok
    before=(project/'project.json').read_bytes()
    refused=new.verify(project,compiler='gcc')
    assert not refused.ok and refused.diagnostics[0]['code']=='SDK_DOCUMENTATION_REQUIRED'
    assert (project/'project.json').read_bytes()==before
    assert new.prepare_documentation(project).ok
    assert not new.scan(project).ok  # Generated blanks require author work.
    starter=tmp_path/'documented-starter'
    assert new.create_project(starter,author='Documentation author').ok
    data=json.loads((project/'project.json').read_text())
    data['documentation']=json.loads((starter/'project.json').read_text())['documentation']
    (project/'project.json').write_text(json.dumps(data))
    verified=new.verify(project,compiler='gcc')
    assert verified.ok,verified.to_dict()
    package=tmp_path/'documented.pcfplugin'
    assert new.build(project,package).ok
    # An old engine rejects the new envelope explicitly even when its scalar
    # operations would fit the older profile; it cannot silently ignore Help.
    old_again=SDK(engine_python=legacy,cache=tmp_path/'old-cache')
    registered=old_again.register(package,store=tmp_path/'old-registry.json')
    assert registered.status=='rejected',registered.to_dict()
