#!/usr/bin/env python3
"""Measure ICMP RTT from this computer. Standard library only; no upload."""
import argparse, json, os, re, subprocess, platform, time
from datetime import datetime, timezone

def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('target'); p.add_argument('--count', type=int, default=30)
    a = p.parse_args()
    if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.:-]{0,252}', a.target) or not 5 <= a.count <= 120:
        p.error('Use a hostname/IP and 5..120 samples.')
    system = platform.system(); samples = []
    for i in range(a.count):
        if system == 'Windows': cmd = ['ping', '-n', '1', '-w', '1000', a.target]
        elif system == 'Darwin': cmd = ['ping6' if ':' in a.target else 'ping', '-c', '1', '-W', '1000', a.target]
        else: cmd = ['ping', '-c', '1', '-W', '1', a.target]
        env = os.environ.copy(); env['LC_ALL'] = 'C'
        try:
            r = subprocess.run(cmd, capture_output=True, text=True, errors='replace', timeout=4, env=env)
            m = re.search(r'(?:time|시간)\s*([=<])\s*([\d.]+)\s*ms', r.stdout, re.I)
            value = float(m[2]) if r.returncode == 0 and m else None
            if m and m[1] == '<': value = float(m[2]) / 2  # approximate upper-bound sample
        except (OSError, subprocess.TimeoutExpired): value = None
        samples.append(value); print(f'{i+1}/{a.count}: {value} ms'); time.sleep(.5)
    with open('line-quality-result.json', 'w', encoding='utf-8') as f:
        json.dump({'target': a.target, 'source': 'PC ICMP via OS ping', 'measuredAt': datetime.now(timezone.utc).isoformat(), 'samples': samples}, f, ensure_ascii=False)
    print('Saved line-quality-result.json; null means timeout, missing ping, or unrecognized response.')
if __name__ == '__main__': main()
