"""Probe failures must never turn a PCFC11 driver into an ordinary C compiler."""
import json
from pathlib import Path
from unittest.mock import patch

import pytest

from pycforge_sdk.native import check_compiler, compiler_identity, execute_fixture
from pycforge_sdk.process import ProcessResult
from pycforge_sdk.results import SDKError


PROFILE = {'hosts': ['Linux'], 'compile_args': [], 'link_args': [], 'compiler_version_args': ['--version'],
           'pcfc11_backend_identity': 'pcfc11.backend/1'}


def identity(driver, profile=PROFILE):
    return compiler_identity(driver, profile, timeout=10, cancel=None)


def executable(path, contents):
    path.write_text(contents)
    path.chmod(0o755)
    return path


@pytest.fixture
def selection(tmp_path, monkeypatch):
    driver = executable(tmp_path/'renamed-driver', '#!/bin/sh\nexit 1\n')
    backend = executable(tmp_path/'actual-gcc', '#!/bin/sh\nexit 2\n')
    link = tmp_path/'gcc alias'
    link.symlink_to(backend)
    reply = {'schema': 'pcfc11.backend/1', 'command': str(link), 'target': 'x86_64-linux-gnu',
             'environment': 'PCFC11_LINUX_CC'}

    def probe(argv, **kwargs):
        assert argv[0] == str(driver)
        if argv[1:] == ['--version']:
            data = b'PCFC11 0.2.32 (x86_64-linux-gnu)\n'
        elif argv[1:] == ['--info-json']:
            data = json.dumps({'schema':1,'name':'PCFC11','version':'0.2.32','process_api':1,
                               'target':'x86_64-linux-gnu','diagnostics_json':True}).encode()
        else:
            data = json.dumps(reply).encode()
        return ProcessResult(0, data, b'')

    monkeypatch.setattr('pycforge_sdk.native.run', probe)
    return driver, backend, reply


def test_backend_path_digest_and_pin_match_the_invocation(selection, tmp_path):
    driver, backend, reply = selection
    previous = identity(driver)
    dep = previous['backend']
    assert dep['executable'] == reply['command'] and dep['resolved'] == str(backend)
    assert len(dep['sha256']) == 64
    with patch('pycforge_sdk.native.run', return_value=ProcessResult(1, b'', b'expected')) as build:
        execute_fixture('C', {}, previous, tmp_path, timeout=10, cancel=None)
    assert build.call_args.kwargs['env']['PCFC11_LINUX_CC'] == reply['command']
    other = executable(tmp_path/'other-gcc', backend.read_text())
    reply['command'] = str(other)
    with pytest.raises(SDKError) as mismatch:
        check_compiler(previous, driver, PROFILE, timeout=10, cancel=None)
    assert mismatch.value.code == 'SDK_STALE_COMPILER'
    assert mismatch.value.details['current_backend']['sha256'] == dep['sha256']


def test_in_place_change_symlink_retarget_and_missing_backend(selection, tmp_path):
    driver, backend, reply = selection
    first = identity(driver)
    executable(backend, '#!/bin/sh\nexit 3\n')
    assert identity(driver)['backend']['sha256'] != first['backend']['sha256']
    alternate = executable(tmp_path/'replacement', backend.read_text())
    link = Path(reply['command'])
    link.unlink(); link.symlink_to(alternate)
    assert identity(driver)['backend']['resolved'] == str(alternate)
    alternate.unlink()
    with pytest.raises(SDKError, match='missing or is not executable') as failure:
        identity(driver)
    assert failure.value.code == 'SDK_COMPILER_BACKEND'


@pytest.mark.parametrize('field,value', [('target','x86_64-w64-mingw32'), ('schema','unknown'),
                                         ('environment','PATH'), ('command',''), ('command',None)])
def test_incompatible_replies_fail_closed(selection, field, value):
    driver, _, reply = selection
    reply[field] = value
    with pytest.raises(SDKError):
        identity(driver)


def test_old_profile_refuses_pcfc11_and_direct_gcc_remains_available(selection):
    driver, _, _ = selection
    legacy = {k:v for k,v in PROFILE.items() if k != 'pcfc11_backend_identity'}
    with pytest.raises(SDKError) as refused:
        identity(driver, legacy)
    assert refused.value.code == 'SDK_BACKEND_CAPABILITY'
    with patch('pycforge_sdk.native.run', return_value=ProcessResult(0, b'gcc (GCC)\n', b'')) as direct:
        assert 'backend' not in identity(driver, legacy)
        assert direct.call_count == 1


def test_recursive_backend_is_refused(selection):
    driver, _, reply = selection
    reply['command'] = str(driver)
    with pytest.raises(SDKError, match='cannot use itself'):
        identity(driver)


@pytest.mark.parametrize('change',[{'schema':True},{'process_api':True},{'diagnostics_json':False},
                                  {'target':'windows-x64'},{'version':'unrelated'},{'error_codes':True}])
def test_diagnostic_capability_is_not_inferred_from_driver_name(selection,monkeypatch,change):
    from pycforge_sdk import native
    driver,_,_=selection
    original=native.run
    def probe(argv,**kwargs):
        result=original(argv,**kwargs)
        if '--info-json' in argv:
            info=json.loads(result.stdout);info.update(change)
            return ProcessResult(0,json.dumps(info).encode(),b'')
        return result
    monkeypatch.setattr(native,'run',probe)
    with pytest.raises(SDKError) as refused:identity(driver)
    assert refused.value.code=='SDK_COMPILER_DIAGNOSTICS'
