# python3 test/app_version_test.py：appCenterUsage.app_version 在临时 docroot 上的行为
import importlib.util, json, os, sys, tempfile
sys.dont_write_bytecode = True  # 不在仓库里留 __pycache__

spec = importlib.util.spec_from_file_location('usage', os.path.join(os.path.dirname(__file__), '..', 'AadenDeploy', 'appCenterUsage.py'))
usage = importlib.util.module_from_spec(spec)
sys.argv = [sys.argv[0], '/nonexistent']
spec.loader.exec_module(usage)

root = tempfile.mkdtemp()
usage.DOCROOT = root
def mk(rel, html, **files):
    d = os.path.join(root, rel); os.makedirs(d)
    open(os.path.join(d, 'index.html'), 'w').write(html)
    for name, content in files.items():
        open(os.path.join(d, name.replace('_', '.', 1) if name != 'appcenter_manifest' else '.appcenter-manifest'), 'w').write(content)

# AppCenter 应用：有 version.json 和 .appcenter-manifest
mk('AppCenter/AdminV3', '<script src=js/chunk-vendors.11111111.js></script><script src=js/app.3960d167.js></script>',
   version_json=json.dumps({'version': '3.0.2', 'commit': 'abcdef123456'}), appcenter_manifest='x  index.html\n')
v = usage.app_version('AppCenter/AdminV3')
assert v['version'] == '3.0.2' and v['commit'] == 'abcdef123456', v
assert len(v['treeSha']) == 64 and v['mainJs'] == 'js/app.3960d167.js' and len(v['fingerprint']) == 16, v

# 根目录老前端：没有 version.json，只有指纹；老版 Vite 入口
mk('Board', '<script type="module" crossorigin src="./assets/index.ce3abdc3.js"></script>')
v = usage.app_version('Board')
assert v['version'] == 'unknown' and 'treeSha' not in v and v['mainJs'] == 'assets/index.ce3abdc3.js', v

# 新版 Vite 入口 + package.json 兜底
mk('KDS3', '<script src="/assets/index-AbCd1234.js"></script>', package_json='{"version":"0.6.1"}')
v = usage.app_version('KDS3')
assert v['version'] == '0.6.1' and v['mainJs'] == 'assets/index-AbCd1234.js', v

# 坏掉的 version.json 不影响其它字段；没有 index.html 只报 unknown
mk('Broken', '<p>x</p>', version_json='{not json')
v = usage.app_version('Broken')
assert v['version'] == 'unknown' and 'fingerprint' in v and 'mainJs' not in v, v
assert usage.app_version('Missing') == {'version': 'unknown'}

print('app-version: ok')

# 兜底：内部抛任何异常都只返回 unknown
orig = usage._app_version
usage._app_version = lambda rel: 1 / 0
assert usage.app_version('AppCenter/AdminV3') == {'version': 'unknown'}
usage._app_version = orig
print('app-version fallback: ok')
