"""Forward-compatible fields and advisory workflow use existing shared contracts."""
import copy
import json
import subprocess
import sys
import threading
from dataclasses import replace
import pytest
from pycforge_sdk import SDK
from pycforge_sdk.fields import option_for, report
from pycforge_sdk.guidance import readiness_guidance
from pycforge_sdk.project import Project, canonical
from pycforge_sdk.workbench import validate


def test_missing_engine_fields_are_discoverable_inert_and_preserve_optional_data(sdk, project, monkeypatch):
    assert sdk.connect().ok
    snapshot = sdk._connection.snapshot
    workbench = json.loads(snapshot.files['workbench.json'])
    document = sdk.open_project(project).data['document']
    profile = copy.deepcopy(next(p for p in workbench['profiles'] if p['declaration_schema'] == document['declaration']['schema']))
    profile['declaration_schema'] = 'future.authoring-contract/1'
    profile['fields'].append({'name':'future_project','title':'Future project data','kind':'json','optional_note':{'engine':'owns this'}})
    definition = {'name':'units','title':'Units from the engine','kind':'text','description':'Engine-defined units.',
                  'future_optional_metadata':{'preserve':[True,1,1.0]}}
    profile['function_fields'].append(definition)
    workbench['profiles'].append(profile)
    value = validate(replace(snapshot, files={**snapshot.files,'workbench.json':canonical(workbench)}))
    monkeypatch.setattr(sdk._connection, 'workbench', lambda: value)
    def forbidden(*args, **kwargs): raise AssertionError('Field browsing must not execute engine authoring actions')
    monkeypatch.setattr(sdk._connection, 'call', forbidden)
    document['declaration']['schema'] = profile['declaration_schema']
    document['declaration']['future_unrepresented'] = {'nested':['preserve this']}
    document['declaration']['functions'][0]['future_value'] = {'version':99}
    (project/'project.json').write_bytes(canonical(document))
    before = Project.load(project)
    declaration = sdk.authoring_fields(project)
    assert declaration.ok and declaration.data['authoring_fields']['fields'][-1]['present'] is False
    assert 'future_unrepresented' in declaration.data['authoring_fields']['unrepresented_fields']
    fields = sdk.authoring_fields(project, function=document['declaration']['functions'][0]['export'])
    assert fields.ok, fields.to_dict()
    field = fields.data['authoring_fields']['fields'][-1]
    assert field == {'definition':definition,'path':'/declaration/functions/0/units','present':False}
    assert 'future_value' in fields.data['authoring_fields']['unrepresented_fields']
    assert fields.data['authoring_fields']['assessment'] == 'not-performed'
    assert Project.load(project).sha256 == before.sha256 and not before.report_path.exists()
    # Explicit edits retain opaque engine-owned additions through the ordinary save.
    document['declaration']['functions'][0]['units'] = 'dimensionless'
    assert sdk.save_project(project, document, expected_sha256=before.sha256).ok
    assert Project.load(project).document == document
    now = sdk.authoring_fields(project, function=document['declaration']['functions'][0]['export'])
    assert now.data['authoring_fields']['fields'][-1]['value'] == 'dimensionless'


def test_complete_reference_retains_new_optional_sections_without_dispatch(sdk,monkeypatch):
    assert sdk.connect().ok
    snapshot=sdk._connection.snapshot
    reference=json.loads(snapshot.files['authoring.json'])
    reference['future_operation_reference']={'arbitrary_namespace':{'new':True}}
    sdk._connection.snapshot=replace(snapshot,files={**snapshot.files,'authoring.json':canonical(reference)})
    def forbidden(*args,**kwargs):raise AssertionError('Reference browsing cannot call authoring actions')
    monkeypatch.setattr(sdk._connection,'call',forbidden)
    result=sdk.engine_reference()
    assert result.ok and result.data['reference']['future_operation_reference']==reference['future_operation_reference']
    result.data['reference']['future_operation_reference']['arbitrary_namespace']['new']=False
    assert sdk.engine_reference().data['reference']['future_operation_reference']['arbitrary_namespace']['new'] is True


def test_complete_reference_cli_matches_python_and_offline_no_cache_never_discovers(sdk,engine_python,tmp_path,monkeypatch):
    direct=sdk.engine_reference()
    process=subprocess.run([sys.executable,'-m','pycforge_sdk','--json','--engine-python',str(engine_python),
        '--cache',str(sdk._connection.cache),'reference'],capture_output=True,text=True,timeout=40)
    assert process.returncode==0 and json.loads(process.stdout)==direct.to_dict()
    isolated=SDK(engine_python='must-not-run',cache=tmp_path/'empty-cache')
    def forbidden():raise AssertionError('Offline browsing must not discover')
    monkeypatch.setattr(isolated._connection,'discover',forbidden)
    assert isolated.engine_reference(offline=True).status=='incomplete'
    assert not isolated._connection.cache.exists()


def test_fields_cli_and_python_share_live_and_explicit_offline_results(sdk, project, engine_python, tmp_path):
    export = Project.load(project).document['declaration']['functions'][0]['export']
    direct = sdk.authoring_fields(project, function=export)
    args = [sys.executable,'-m','pycforge_sdk','--engine-python',str(engine_python),
            '--cache',str(sdk._connection.cache),'fields',str(project),'--function',export]
    process = subprocess.run([*args[:3],'--json',*args[3:]],capture_output=True,text=True,timeout=40)
    assert process.returncode == 0 and json.loads(process.stdout) == direct.to_dict()
    offline = sdk.authoring_fields(project, function=export, offline=True)
    args[4] = str(tmp_path/'missing-engine')
    process = subprocess.run([*args[:3],'--json',*args[3:],'--offline'],capture_output=True,text=True,timeout=40)
    assert process.returncode == 0 and json.loads(process.stdout) == offline.to_dict()
    text = subprocess.run([*args,'--offline'],capture_output=True,text=True,timeout=40)
    assert text.returncode == 0 and 'Connection: offline' in text.stdout and 'Current:' in text.stdout


def test_offline_fields_without_cache_do_not_discover_or_mutate(project, tmp_path, monkeypatch):
    sdk = SDK(engine_python=tmp_path/'must-not-run',cache=tmp_path/'no-cache')
    def forbidden(): raise AssertionError('Offline fields must not run discovery')
    monkeypatch.setattr(sdk._connection,'discover',forbidden)
    before = Project.load(project).sha256
    result = sdk.authoring_fields(project,offline=True)
    assert result.status == 'incomplete' and result.diagnostics[0]['code'] == 'SDK_ENGINE_UNAVAILABLE'
    assert Project.load(project).sha256 == before and not sdk._connection.cache.exists()


@pytest.mark.parametrize('selection', ['', False, 'missing-function'])
def test_invalid_function_selection_is_structured_and_preserves_project(sdk, project, selection):
    before = Project.load(project).sha256
    value = sdk.authoring_fields(project,function=selection)
    assert value.status == 'rejected' and value.diagnostics[0]['code'] in ('SDK_ARGUMENT','SDK_FIELD_TARGET')
    assert Project.load(project).sha256 == before


def test_unknown_profile_and_ambiguous_function_do_not_infer_a_form(sdk, project):
    doc = sdk.open_project(project).data['document']; workbench = sdk.workbench().data['workbench']
    doc['declaration']['schema'] = 'unknown.future/7'
    value = report(doc, workbench)
    assert value['source'] == 'no-advertised-form' and not value['fields']
    assert 'functions' in value['unrepresented_fields']
    doc['declaration']['functions'].append(copy.deepcopy(doc['declaration']['functions'][0]))
    (project/'project.json').write_bytes(canonical(doc))
    value = sdk.authoring_fields(project,function=doc['declaration']['functions'][0]['export'])
    assert value.diagnostics[0]['code'] == 'SDK_FIELD_TARGET'
    assert len(value.diagnostics[0]['details']['functions']) == 2


def test_fields_cancellation_precedes_discovery(sdk, project, tmp_path):
    event = threading.Event(); event.set()
    sdk = SDK(engine_python='missing',cache=tmp_path/'unused',cancel=event)
    assert sdk.authoring_fields(project).status == 'canceled'
    assert not sdk._connection.cache.exists()


def test_typed_engine_choices_keep_distinct_identity():
    values = [True,1,1.0,'1',None]
    definition = {'options':[{'value':value,'title':str(index)} for index,value in enumerate(values)]}
    assert [option_for(definition,value)['title'] for value in values] == ['0','1','2','3','4']
    assert option_for(definition,False) is None


@pytest.mark.parametrize('state,ready', [('future-state',True),('ready-to-package',False),('canceled',False)])
def test_unknown_or_unapproved_guidance_cannot_offer_packaging(state, ready):
    value = {'state':state,'ready':ready,'future_metadata':{'preserved':True}}
    before = copy.deepcopy(value)
    guide = readiness_guidance(value)
    assert guide['advisory_only'] and all(a['explicit_action_required'] for a in guide['actions'])
    assert not any(a['method'] in ('build','verify') for a in guide['actions'])
    assert value == before


def test_readiness_guidance_is_shared_and_does_not_run_or_write_fixtures(sdk, project, monkeypatch):
    import pycforge_sdk.service as service
    def forbidden(*args,**kwargs): raise AssertionError('Advice cannot execute fixtures')
    monkeypatch.setattr(service,'execute_fixture',forbidden)
    before = Project.load(project)
    result = sdk.readiness(project,compiler='gcc')
    assert result.data['readiness']['state'] == 'ready-to-verify'
    guide = result.data['readiness']['guidance']
    assert {a['method'] for a in guide['actions']} == {None,'preflight','verify'}
    assert 'native-execution' in next(a for a in guide['actions'] if a['method']=='verify')['effects']
    assert Project.load(project).sha256 == before.sha256 and not before.report_path.exists()


def test_project_growth_uses_byte_budget_instead_of_a_fixture_count(sdk,project):
    opened=sdk.open_project(project).data;document=opened['document']
    for index in range(100):
        case=copy.deepcopy(document['cases'][-1]);case['name']='additional_'+str(index)
        document['cases'].append(case)
    saved=sdk.save_project(project,document,expected_sha256=opened['project_sha256'])
    assert saved.ok,saved.to_dict()
    assert len(Project.load(project).document['cases'])==102
    assert not Project.load(project).report_path.exists()


def test_aggregate_source_budget_stops_before_reading_remaining_files(tmp_path,monkeypatch):
    import pycforge_sdk.project as model
    document={'schema':model.PROJECT_SCHEMA,'declaration':{},
              'metadata':{'author':'a','created':'x','description':'d','license':'l'},
              'cases':[{'name':str(i),'file':str(i)+'.py',
                        'expect':{'kind':'reject','code':'PYC4706'}} for i in range(5)]}
    data=canonical(document);(tmp_path/'project.json').write_bytes(data)
    for i in range(5):(tmp_path/(str(i)+'.py')).write_bytes(b' '*512)
    monkeypatch.setattr(model,'MAX_PROJECT',len(data)+700)
    original=model.read;seen=[]
    def observed(path,limit):
        seen.append((path.name,limit));return original(path,limit)
    monkeypatch.setattr(model,'read',observed)
    with pytest.raises(model.SDKError):Project.load(tmp_path)
    assert [name for name,_ in seen]==['project.json','0.py','1.py']
    assert seen[-1][1]==188
