"""Installed-client authoring through the selected engine, without local engine imports."""
import json
import os
import subprocess
import sys
from pathlib import Path

from pycforge_sdk import SDK
from pycforge_sdk.project import Project


def test_template_preview_is_inert_and_detached(sdk, tmp_path):
    assert sdk.connect().ok
    before = set(tmp_path.iterdir())
    preview = sdk.template('scalar-cube-root')
    assert preview.ok and preview.data['verification'] == 'not-established'
    preview.data['template']['declaration']['namespace'] = 'changed'
    assert sdk.template('scalar-cube-root').data['template']['declaration']['namespace'] == 'example'
    assert set(tmp_path.iterdir()) == before
    assert not sdk.template('absent').ok


def test_customized_project_native_package_and_stale_preservation(sdk, tmp_path):
    root = tmp_path/'independent'
    created = sdk.create_project(root, author='SDK author', package_id='org.example.measure',
                                 namespace='measure', exports={'cbrt': 'cube_root'})
    assert created.ok, created.to_dict()
    doc = Project.load(root).document
    assert doc['declaration']['functions'][0]['export'] == 'cube_root'
    assert 'e.cube_root' in (root/doc['cases'][0]['file']).read_text()
    assert sdk.scan(root).ok
    assert not sdk.build(root, tmp_path/'measure.pcfplugin').ok
    assert sdk.verify(root, compiler='gcc').ok
    assert sdk.readiness(root, compiler='gcc').ok
    package = tmp_path/'measure.pcfplugin'
    assert sdk.build(root, package).ok
    contents = package.read_bytes()
    assert sdk.build(root, package).ok and package.read_bytes() == contents
    assert sdk.register(package, store=tmp_path/'registry').ok
    snapshot = sdk.open_project(root).data
    snapshot['document']['metadata']['description'] += ' Updated'
    assert sdk.save_project(root, snapshot['document'], expected_sha256=snapshot['project_sha256']).ok
    assert not sdk.build(root, package).ok and package.read_bytes() == contents


def test_refusals_do_not_create_or_overwrite_projects(sdk, tmp_path):
    path = tmp_path/'refused'
    args = dict(author='Author', package_id='org.example.custom', namespace='custom')
    result = sdk.create_project(path, exports={'missing': 'test'}, **args)
    assert not result.ok and result.diagnostics[0]['code'] == 'CRU2700' and not path.exists()
    assert not sdk.create_project(path, author='Author', namespace='custom').ok
    assert sdk.create_project(path, **args).ok
    before = {str(p.relative_to(path)): p.read_bytes() for p in path.rglob('*') if p.is_file()}
    assert not sdk.create_project(path, **args).ok
    assert before == {str(p.relative_to(path)): p.read_bytes() for p in path.rglob('*') if p.is_file()}


def test_offline_preview_and_customization_boundary(sdk, tmp_path):
    assert sdk.connect().ok
    assert sdk.connect(offline=True).data['state'] == 'offline'
    assert sdk.template('scalar-cube-root').ok
    result = sdk.create_project(tmp_path/'offline', author='Author', package_id='org.test.custom', namespace='custom')
    assert result.status == 'incomplete' and result.diagnostics[0]['code'] == 'SDK_OFFLINE'
    assert not (tmp_path/'offline').exists()


def test_prior_engine_retains_plain_starter_and_refuses_customization(tmp_path):
    client = SDK(engine_python=os.environ['PYCFORGE_PREVIOUS_ENGINE'], cache=tmp_path/'cache')
    assert client.create_project(tmp_path/'plain', author='Author').ok
    result = client.create_project(tmp_path/'custom', author='Author', package_id='org.test.custom', namespace='custom')
    assert not result.ok and result.diagnostics[0]['code'] == 'SDK_CAPABILITY'
    assert not (tmp_path/'custom').exists()


def test_json_cli_creates_custom_project_and_reports_bad_mapping(tmp_path, engine_python):
    command = [sys.executable, '-m', 'pycforge_sdk', '--json', '--engine-python', str(engine_python),
               '--cache', str(tmp_path/'cache')]
    args = ['new', str(tmp_path/'cli'), '--author', 'Author', '--package-id', 'org.test.cli',
            '--namespace', 'cli_import', '--rename', 'cbrt=cube_root']
    run = subprocess.run(command + args, capture_output=True, text=True, timeout=60)
    assert run.returncode == 0, run.stdout + run.stderr
    assert json.loads(run.stdout)['status'] == 'succeeded'
    bad = subprocess.run(command + args + ['--rename', 'cbrt=duplicate'], capture_output=True, text=True, timeout=60)
    assert bad.returncode == 2 and json.loads(bad.stdout)['diagnostics'][0]['code'] == 'SDK_ARGUMENT'
    detail = subprocess.run(command + ['template', 'scalar-cube-root'], capture_output=True, text=True, timeout=60)
    assert detail.returncode == 0 and json.loads(detail.stdout)['data']['template']['cases']
