# -*- coding: utf-8 -*-
r"""B105: kiểm kê app đang chạy (cổng, tiến trình) + file của từng app liên quan MÀU và QUY TRÌNH."""
import glob, os, re, subprocess

def sh(c, t=60):
    try:
        r = subprocess.run(c, shell=True, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=t)
        return ((r.stdout or '') + (r.stderr or '')).strip()
    except Exception as e:
        return 'LOI %s' % e

print('=== 1) CỔNG ĐANG MỞ (LISTEN) ===')
net = sh('netstat -ano | findstr LISTENING')
for port in (8080, 8095, 8098, 8099, 8100, 18789):
    dong = [x.strip() for x in net.splitlines() if ':%d ' % port in x or x.strip().endswith(':%d' % port)]
    print('  %-6d %s' % (port, dong[0] if dong else 'KHÔNG nghe'))

print()
print('=== 2) TIẾN TRÌNH python đang chạy (server/worker) ===')
ps = sh('powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"name like \'python%\'\\" | Select-Object ProcessId,CommandLine | Format-Table -Wrap -AutoSize | Out-String -Width 300"', 90)
for x in ps.splitlines():
    if re.search(r'server_|worker|agent|calib|hlqt|lab|portal', x, re.I):
        print('  ', x.strip()[:230])

print()
print('=== 3) FILE ỨNG DỤNG trên đĩa ===')
mau = {}
for pat in (r'C:\Claw 2\Nghien cuu\**\server_*.py', r'C:\Claw 2\**\server_*.py', r'C:\c\deepseek-harness\**\server_*.py',
            r'C:\Claw 2\**\worker*.py', r'C:\Claw 2\**\build_*portal*.py', r'C:\Claw 2\**\build_lam_mau*.py'):
    for f in glob.glob(pat, recursive=True):
        mau[f] = os.path.getsize(f)
for f in sorted(mau):
    print('  %8d B  %s' % (mau[f], f))
