import base64
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
import pytest
from pycforge_sdk import SDK
from pycforge_sdk.project import Project, canonical, parse, digest


def test_separate_python_api_workflow_and_deterministic_package(sdk,project,tmp_path):
    assert sdk.connect().ok
    methods=sdk.methods(); assert methods.ok and len(methods.data['methods'])>=6
    description=sdk.describe('ScalarAuthoring.convert')
    assert description.ok and {'source','logical_name'}=={p['name'] for p in description.data['method']['parameters']}
    info=sdk.inspect(project); assert info.ok and info.data['inspection']['verification']=='not-established'
    missing=sdk.build(project,tmp_path/'not_verified.pcfplugin')
    assert missing.status=='rejected' and missing.diagnostics[0]['code']=='SDK_VERIFICATION_REQUIRED'
    verified=sdk.verify(project,compiler='gcc'); assert verified.ok,verified.to_dict()
    assert [case['passed'] for case in verified.data['report']['cases']]==[True,True]
    a,b=tmp_path/'a.pcfplugin',tmp_path/'b.pcfplugin'
    assert sdk.build(project,a).ok and sdk.build(project,b).ok
    assert a.read_bytes()==b.read_bytes()
    registered=sdk.register(a,store=tmp_path/'registration'/'registry.json')
    assert registered.ok and registered.data['registration']['namespace']=='example'
    assert not any(n=='pycforge' or n.startswith(('pycforge.','PySide6')) for n in sys.modules)


def test_python_and_console_use_same_service_results(sdk,project,tmp_path,engine_python):
    direct=sdk.inspect(project)
    completed=subprocess.run([sys.executable,'-m','pycforge_sdk','--engine-python',str(engine_python),
        '--cache',str(tmp_path/'cli_cache'),'--json','inspect',str(project)],capture_output=True,text=True,timeout=30)
    assert completed.returncode==0,completed.stderr
    assert json.loads(completed.stdout)==direct.to_dict()
    failed=subprocess.run([sys.executable,'-m','pycforge_sdk','--engine-python',str(engine_python),
        '--cache',str(tmp_path/'cli_cache'),'--json','convert',str(project),'--case','wrong-argument-count'],
        capture_output=True,text=True,timeout=30)
    assert failed.returncode==2
    answer=json.loads(failed.stdout)
    assert answer['status']=='rejected' and answer['data']['conversion']['diagnostics'][0]['code']=='PYC4706'


@pytest.mark.parametrize('damage',['source','expectation','metadata','declaration','report','engine','compiler'])
def test_no_stale_verification_can_build(sdk,project,tmp_path,damage):
    assert sdk.verify(project,compiler='gcc').ok
    path=project/'project.json'
    if damage=='source':
        source=project/'tests/case_1.py'; source.write_text(source.read_text()+'\n')
    elif damage in ('expectation','metadata','declaration'):
        data=parse(path.read_bytes())
        if damage=='expectation': data['cases'][0]['expect']['stdout']='wrong\n'
        if damage=='metadata': data['metadata']['author']='Changed author'
        if damage=='declaration': data['declaration']['version']='0.1.1'
        path.write_bytes(canonical(data))
    else:
        report_path=Project.load(project).report_path; data=parse(report_path.read_bytes())
        if damage=='report': data['cases'][0]['passed']=False
        if damage=='engine': data['engine']['engine_version']='99.0.0'
        if damage=='compiler': data['compiler']['sha256']='0'*64
        data['evidence_sha256']=digest(canonical({k:v for k,v in data.items() if k!='evidence_sha256'}))
        report_path.write_bytes(canonical(data))
    destination=tmp_path/'blocked.pcfplugin'
    result=sdk.build(project,destination)
    assert not result.ok and not destination.exists(),result.to_dict()
    assert result.status!='internal_failure',result.to_dict()


def test_failed_new_run_retires_previous_passing_report(sdk,project,tmp_path):
    assert sdk.verify(project,compiler='gcc').ok
    result=sdk.verify(project,compiler='compiler-that-does-not-exist')
    assert not result.ok and result.status=='incomplete'
    assert parse(Project.load(project).report_path.read_bytes())['status']=='incomplete'
    assert not sdk.build(project,tmp_path/'blocked.pcfplugin').ok


def test_failing_fixture_preserves_existing_package(sdk,project,tmp_path):
    destination=tmp_path/'existing.pcfplugin'; destination.write_bytes(b'previous package')
    path=project/'project.json'; data=parse(path.read_bytes())
    data['cases'][0]['expect']['stdout']='incorrect\n'; path.write_bytes(canonical(data))
    result=sdk.verify(project,compiler='gcc')
    assert result.status=='rejected' and result.data['report']['status']=='failed'
    assert not sdk.build(project,destination).ok
    assert destination.read_bytes()==b'previous package'


def test_cancel_and_progress_share_headless_service(sdk,project,tmp_path,engine_python):
    event=threading.Event(); seen=[]
    def progress(message):
        seen.append(message); event.set()
    client=SDK(engine_python=engine_python,cache=tmp_path/'cancel_cache',cancel=event,progress=progress)
    result=client.verify(project,compiler='gcc')
    assert result.status=='canceled' and seen[0]['phase']=='case'
    assert parse(Project.load(project).report_path.read_bytes())['status']=='canceled'
    assert not sdk.build(project,tmp_path/'blocked.pcfplugin').ok


def test_offline_cache_can_explain_but_cannot_execute(sdk,project,tmp_path):
    assert sdk.connect().ok
    client=SDK(engine_python=tmp_path/'missing-python',cache=tmp_path/'cache')
    state=client.connect()
    assert state.status=='incomplete' and state.data['state']=='offline'
    assert client.describe('ScalarAuthoring').ok
    result=client.inspect(project)
    assert result.status=='incomplete' and result.diagnostics[0]['code']=='SDK_OFFLINE'


def test_missing_service_is_visible_and_legacy_catalogue_is_browsable(tmp_path):
    old=os.environ.get('PYCFORGE_TEST_OLD_ENGINE')
    assert old,'Set PYCFORGE_TEST_OLD_ENGINE for installed legacy compatibility checks.'
    client=SDK(engine_python=old,cache=tmp_path/'cache')
    connection=client.connect()
    assert connection.ok and not connection.data['execution_available'] and client.methods(advanced=True).ok
    failure=client.methods()
    assert failure.status=='rejected' and failure.diagnostics[0]['code']=='SDK_CAPABILITY'


def test_project_changes_during_work_do_not_receive_evidence(sdk,project,tmp_path,engine_python):
    def progress(_):
        source=project/'tests/case_1.py';source.write_text(source.read_text()+'\n')
    client=SDK(engine_python=engine_python,cache=tmp_path/'changed_cache',progress=progress)
    result=client.verify(project,compiler='gcc')
    assert result.status=='rejected' and result.diagnostics[0]['code']=='SDK_STALE_PROJECT'
    assert not sdk.build(project,tmp_path/'blocked.pcfplugin').ok


def test_missing_negative_fixtures_cannot_claim_complete_verification(sdk,project):
    path=project/'project.json';data=parse(path.read_bytes());data['cases']=data['cases'][:1];path.write_bytes(canonical(data))
    result=sdk.verify(project,compiler='gcc')
    assert result.status=='rejected' and result.diagnostics[0]['code']=='SDK_INCOMPLETE_SUITE'


def test_project_creation_never_overwrites_an_existing_directory(sdk,project):
    before=(project/'project.json').read_bytes()
    result=sdk.create_project(project,author='Other author')
    assert result.status=='rejected' and (project/'project.json').read_bytes()==before


def test_malformed_report_is_a_rejection_not_a_crash(sdk,project,tmp_path):
    report=Project.load(project).report_path
    report.parent.mkdir(exist_ok=True);report.write_text('[]')
    result=sdk.build(project,tmp_path/'blocked.pcfplugin')
    assert result.status=='rejected' and result.diagnostics[0]['code']=='SDK_EVIDENCE'


def test_invalid_json_command_reports_structured_argument_error():
    command = [sys.executable, '-m', 'pycforge_sdk', '--json', 'verify']
    result = subprocess.run(command, capture_output=True, text=True, timeout=10)
    assert result.returncode == 2 and result.stderr == ''
    reply = json.loads(result.stdout)
    assert reply['status'] == 'rejected' and reply['diagnostics'][0]['code'] == 'SDK_ARGUMENT'
