#!/usr/bin/env python3
"""Collect non-destructive KOPR environment diagnostics, revision 10.12.

The script does not read .env, stored credentials, configuration values or FITS
pixel data. It prints only the optional KOPR_WSL_DISTRIBUTION variable because
that value selects the astrometry backend and is not a credential.
"""
from __future__ import annotations
import importlib
import os
from pathlib import Path
import platform
import shutil
import subprocess
import sys

REQUIRED_MODULES = ['PyQt5', 'numpy', 'scipy', 'matplotlib', 'astropy', 'requests', 'rawpy', 'exifread']
OPTIONAL_MODULES = ['astroquery']


def run(command: list[str], timeout: int = 15) -> tuple[int, str]:
    try:
        kwargs = dict(capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout, check=False)
        if os.name == 'nt': kwargs['creationflags'] = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
        proc = subprocess.run(command, **kwargs)
        return proc.returncode, (proc.stdout or proc.stderr or '').strip()
    except Exception as exc:
        return -1, f'{type(exc).__name__}: {exc}'


def command_version(command: str, args: list[str]) -> str:
    path = shutil.which(command)
    if not path: return 'NOT FOUND'
    rc, text = run([path, *args], timeout=10)
    first = text.splitlines()[0] if text else f'exit {rc}'
    return f'{path} - {first}'


def wsl_prefix(wsl: str) -> list[str]:
    prefix = [wsl]
    distro = (os.environ.get('KOPR_WSL_DISTRIBUTION') or '').strip()
    if distro: prefix += ['--distribution', distro]
    return prefix + ['--exec']


def main() -> int:
    root = Path.cwd()
    print('KOPR DIAGNOSTIC SUMMARY - DOCUMENTATION REVISION 10.12')
    print('====================================================')
    print('Current directory:', root)
    print('kopr.py present:', (root / 'kopr.py').is_file())
    print('Platform:', platform.platform())
    print('Python:', sys.version.replace('\n', ' '))
    print('Executable:', sys.executable)
    print('Virtual environment:', os.environ.get('VIRTUAL_ENV', 'not set'))
    print('\nPython modules:')
    for name in REQUIRED_MODULES:
        try:
            mod = importlib.import_module(name); print(f'  {name}: OK ({getattr(mod, "__version__", "version not exposed")})')
        except Exception as exc:
            print(f'  {name}: FAILED ({type(exc).__name__}: {exc})')
    for name in OPTIONAL_MODULES:
        try:
            mod = importlib.import_module(name); print(f'  {name}: OPTIONAL OK ({getattr(mod, "__version__", "version not exposed")})')
        except Exception as exc:
            print(f'  {name}: OPTIONAL NOT AVAILABLE ({type(exc).__name__}: {exc})')

    print('\nAstrometry solver backends:')
    print('  native solve-field:', command_version('solve-field', ['--help']))
    if os.name == 'nt':
        wsl = shutil.which('wsl.exe') or shutil.which('wsl')
        distro = (os.environ.get('KOPR_WSL_DISTRIBUTION') or '').strip()
        print('  wsl.exe:', wsl or 'NOT FOUND')
        print('  KOPR_WSL_DISTRIBUTION:', distro or 'not set (default WSL distribution)')
        if wsl:
            rc, text = run(wsl_prefix(wsl) + ['sh', '-lc', 'command -v solve-field'])
            path = text.splitlines()[-1].strip() if text.splitlines() else ''
            print('  WSL solve-field:', path if rc == 0 and path else f'NOT FOUND / probe failed ({text or "no output"})')
            rc, text = run([wsl, '--list', '--verbose'])
            print('  WSL distributions:')
            for line in (text.splitlines() if text else [f'probe failed (exit {rc})']): print('   ', line)
    else:
        print('  WSL probe: not applicable on this platform')

    print('\nExpected local paths:')
    for rel in ['config-files', 'comet-data', 'obs-data', 'astrometry-index/4100', 'astrometry-index/4200']:
        path = root / rel; print(f'  {rel}:', 'present' if path.exists() else 'missing')
    idx41 = root / 'astrometry-index' / '4100'
    idx42 = root / 'astrometry-index' / '4200'
    print('  Optional Astrometry 41xx FITS index files:', len(list(idx41.glob('index-41*.fits'))) if idx41.is_dir() else 0)
    print('  Established Astrometry 42xx FITS index files:', len(list(idx42.glob('index-42*.fits'))) if idx42.is_dir() else 0)
    print('  Wide-field recommendation: 4107-4112, 4206-4212')
    print('\nSelected workflow files in current directory:')
    for rel in ['pipeline_state.json', 'processing_manifest.json', 'stats/qc_results.json']:
        print(f'  {rel}:', 'present' if (root / rel).is_file() else 'missing')
    print('\nReview local paths above before sharing this output publicly. Do not send passwords.')
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
