from pathlib import Path
import os
import sys
import threading
import time
import pytest
from pycforge_sdk.project import Project, canonical, parse
from pycforge_sdk.process import run
from pycforge_sdk.results import SDKError


@pytest.mark.parametrize('damage',['traversal','absolute','symlink','directory-symlink','duplicate-json','unknown-field','missing-source','wrong-kind','oversized-source','nonfinite','utf16'])
def test_data_only_project_admission(project,tmp_path,damage):
    path=project/'project.json';data=parse(path.read_bytes())
    if damage=='traversal': data['cases'][0]['file']='../outside.py'
    elif damage=='absolute': data['cases'][0]['file']=str(tmp_path/'outside.py')
    elif damage=='symlink':
        source=project/'tests/case_1.py';source.unlink();source.symlink_to(project/'tests/case_2.py')
    elif damage=='directory-symlink':
        (project/'linked').symlink_to(project/'tests',target_is_directory=True);data['cases'][0]['file']='linked/case_1.py'
    elif damage=='unknown-field': data['execute']='arbitrary'
    elif damage=='missing-source': data['cases'][0]['file']='missing.py'
    elif damage=='wrong-kind': data['cases'][0]['expect']['kind']='unchecked'
    elif damage=='oversized-source': (project/'tests/case_1.py').write_bytes(b' '* (256*1024+1))
    if damage=='duplicate-json': path.write_bytes(b'{"schema":1,"schema":2}')
    elif damage=='nonfinite': path.write_bytes(b'{"schema":NaN}')
    elif damage=='utf16': path.write_bytes(canonical(data).decode().encode('utf-16'))
    else: path.write_bytes(canonical(data))
    with pytest.raises((SDKError,OSError)): Project.load(project)


def test_timeout_stops_a_process_group(tmp_path):
    marker=tmp_path/'child_completed'
    child="import time,pathlib;time.sleep(0.5);pathlib.Path("+repr(str(marker))+").write_text('wrong')"
    parent="import subprocess,sys,time;subprocess.Popen([sys.executable,'-c',"+repr(child)+"]);time.sleep(10)"
    with pytest.raises(SDKError) as error:
        run([sys.executable,'-c',parent],timeout=0.1)
    assert error.value.code=='SDK_TIMEOUT'
    # Bounded observation after the child's intended write time.
    threading.Event().wait(0.6)
    assert not marker.exists()


def test_process_cancellation_and_output_budgets():
    cancel=threading.Event();timer=threading.Timer(0.1,cancel.set);timer.start()
    try:
        with pytest.raises(SDKError) as error:run([sys.executable,'-c','import time;time.sleep(10)'],cancel=cancel)
        assert error.value.status=='canceled'
    finally:timer.cancel()
    with pytest.raises(SDKError) as error:
        run([sys.executable,'-c','import sys;sys.stdout.write("x"*10000)'],max_output=100)
    assert error.value.code=='SDK_OUTPUT_LIMIT'


def test_sdk_import_is_independent_even_without_site_packages():
    import pycforge_sdk
    source=Path(pycforge_sdk.__file__).resolve().parents[1]
    code="import sys;sys.path.insert(0,sys.argv[1]);from pycforge_sdk import SDK;assert not any(n=='pycforge' or n.startswith(('pycforge.','PySide6','numpy','numba')) for n in sys.modules)"
    result=run([sys.executable,'-I','-S','-c',code,str(source)])
    assert result.returncode==0,result.stderr


def test_data_only_registration_with_nan_metadata_does_not_fail_after_activation(sdk,project,tmp_path):
    path=project/'project.json';data=parse(path.read_bytes())
    data['declaration']['constants']=[{'export':'nan','value':'nan'}]
    data['documentation']['constants']['nan']='A quiet NaN classification value.'
    path.write_bytes(canonical(data))
    assert sdk.verify(project,compiler='gcc').ok
    package=tmp_path/'nan.pcfplugin'
    assert sdk.build(project,package).ok
    result=sdk.register(package,store=tmp_path/'registry.json')
    assert result.ok,result.to_dict()

