import importlib.util
from pathlib import Path
from types import SimpleNamespace

import pytest


@pytest.fixture
def dev(tmp_path):
    spec = importlib.util.spec_from_file_location("local_dev_tools", Path(__file__).parents[1] / "tools/dev.py")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    module.REPO = tmp_path / "repo"
    module.ENVIRONMENT = tmp_path / "environment"
    module.NODE = module.ENVIRONMENT / "node"
    module.REPO.mkdir()
    module.NODE.mkdir(parents=True)
    for name in ("package.json", "package-lock.json"):
        (module.REPO / name).write_text("{}")
        (module.NODE / name).write_text("{}")
    return module


def test_build_uses_external_modules_and_keeps_source_assets(dev, monkeypatch):
    calls = []
    monkeypatch.setattr(dev.shutil, "which", lambda name: name)
    monkeypatch.setattr(dev.subprocess, "run", lambda command, **kw: calls.append((command, kw)) or SimpleNamespace(returncode=0))
    asset = dev.REPO / "output.css"
    asset.write_bytes(b"unchanged")
    assert dev.main(["build"]) == 0
    assert len(calls) == 2
    assert {call[0][3] for call in calls} == {"InvestmentWebsite/static/input.css", "InvestmentManager/static/css/input.css"}
    assert all(kw["cwd"] == dev.REPO and kw["env"]["NODE_PATH"] == str(dev.NODE / "node_modules") for _, kw in calls)
    assert asset.read_bytes() == b"unchanged"


def test_build_rejects_output_in_checkout(dev):
    with pytest.raises(SystemExit):
        dev.main(["build", "--output-dir", str(dev.REPO / "static")])


def test_stale_external_manifest_requires_install(dev):
    (dev.NODE / "package-lock.json").write_text('{"stale":true}')
    with pytest.raises(SystemExit):
        dev.main(["npm", "--", "ls"])
