# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform — P34
"""Explicit virtual/physical DHT22 sensor and local/live HTTP experiment."""
import argparse
import getpass
import math
import os
import re
import sys
import time
import warnings
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen

ENDPOINT = 'https://api.thingspeak.com/update'


def validate_key(value):
    key = (value or '').strip()
    # Channel keys are 16 alphanumeric characters. Do not accept URLs or channel IDs.
    if not re.fullmatch(r'[A-Za-z0-9]{16}', key):
        raise ValueError('Enter only the 16-character channel Write API Key from Channels > API Keys (not the Read key, URL or channel ID).')
    return key


def response_entry(status, body):
    if status != 200:
        raise RuntimeError(f'HTTP {status}: update not accepted.')
    body = body.strip()
    if body == '0':
        raise RuntimeError('HTTP 200, entry 0: ThingSpeak rejected the update. Check the channel Write API Key, enabled fields, and wait at least 20 seconds before another attempt. The response alone cannot identify the cause.')
    if not re.fullmatch(r'[0-9]+', body) or int(body) <= 0:
        raise RuntimeError('Unexpected response body; no confirmed entry ID.')
    return int(body)


def upload(t, h, key, source, endpoint=ENDPOINT, opener=urlopen):
    if not (math.isfinite(t) and math.isfinite(h) and -40 <= t <= 80 and 0 <= h <= 100):
        raise ValueError('Invalid DHT22 reading; no upload attempted.')
    payload = urlencode({'api_key': key, 'field1': round(t, 1), 'field2': round(h, 1), 'status': source}).encode('ascii')
    req = Request(endpoint, data=payload, method='POST', headers={'Content-Type': 'application/x-www-form-urlencoded'})
    try:
        with opener(req, timeout=15) as response:
            return response_entry(response.status, response.read(128).decode('ascii', errors='replace'))
    except HTTPError as e:
        hint = {401:'Check the channel Write API Key.',403:'Check channel permissions and Write API Key.',429:'Wait at least 20 seconds and check channel rate limits.'}.get(e.code,'Check channel settings and service availability.')
        raise RuntimeError(f'HTTP {e.code}: {hint}') from None
    except (URLError, TimeoutError, OSError) as e:
        # Never print exception URLs or credentials.
        raise RuntimeError(f'HTTPS/HTTP connection failed ({type(e).__name__}); check DNS, internet, system clock and trusted certificates. Do not disable TLS verification.') from None


def local_trial(t, h):
    from http.server import BaseHTTPRequestHandler, HTTPServer
    from threading import Thread
    from urllib.parse import parse_qs
    rows = []
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, *_): pass
        def do_POST(self):
            data = parse_qs(self.rfile.read(int(self.headers['Content-Length'])).decode())
            if data.get('api_key') == ['LOCALDEMO1234567']:
                rows.append(data); body = str(len(rows)).encode()
            else: body = b'0'
            self.send_response(200); self.end_headers(); self.wfile.write(body)
    server = HTTPServer(('127.0.0.1',0), Handler)
    worker = Thread(target=server.serve_forever, daemon=True); worker.start()
    try:
        endpoint = f'http://127.0.0.1:{server.server_port}/update'
        entry = upload(t,h,'LOCALDEMO1234567','mock',endpoint)
        assert entry == 1 and float(rows[0]['field1'][0]) == round(t,1) and float(rows[0]['field2'][0]) == round(h,1)
        print(f'LOCAL HTTP TEST PASS: entry {entry}; temperature {t:.1f} °C; humidity {h:.1f}%. No cloud write.')
        try: upload(t,h,'wrong','mock',endpoint)
        except RuntimeError: print('LOCAL NEGATIVE TEST PASS: wrong credential rejected (entry 0).')
        else: raise AssertionError('Invalid key accepted by local fixture')
    finally:
        server.shutdown();server.server_close();worker.join()


def sample(args):
    if args.sensor == 'mock':
        return args.temperature, args.humidity
    # Only import physical hardware dependencies when explicitly requested.
    try:
        import board
        import adafruit_dht
        if 'fakepi' in str(getattr(board, '__file__', '')):
            raise RuntimeError('Fake GPIO module detected. Use --sensor mock or deactivate the WSL fakepi environment.')
        device = adafruit_dht.DHT22(board.D23)
    except (ImportError, AttributeError, OSError, RuntimeError) as e:
        raise RuntimeError('Physical DHT22 unavailable. Use --sensor mock in WSL; on a Raspberry Pi install Blinka and Adafruit DHT and verify BCM23 wiring.') from None
    try:
        for i in range(5):
            try:
                t,h=device.temperature,device.humidity
                if t is not None and h is not None and -40 <= t <= 80 and 0 <= h <= 100:
                    return t,h
            except RuntimeError: pass
            if i<4:time.sleep(2.1)
        raise RuntimeError('DHT22 failed after five attempts. No upload performed.')
    finally: device.exit()


def main():
    p=argparse.ArgumentParser(description=__doc__)
    mode=p.add_mutually_exclusive_group();mode.add_argument('--local',action='store_true',help='Loopback HTTP test (default; no real key)');mode.add_argument('--live',action='store_true',help='One real HTTPS update to your own private channel')
    p.add_argument('--sensor',choices=['mock','hardware'],default='mock');p.add_argument('--temperature',type=float,default=24.5);p.add_argument('--humidity',type=float,default=55.0)
    args=p.parse_args()
    try:
        t,h=sample(args)
        if not args.live:
            local_trial(t,h);return 0
        raw=os.getenv('THINGSPEAK_WRITE_KEY','').strip()
        if not raw:
            if not sys.stdin.isatty():raise ValueError('Use an interactive terminal for hidden key entry, or set THINGSPEAK_WRITE_KEY in the current terminal.')
            with warnings.catch_warnings():
                warnings.simplefilter('error',getpass.GetPassWarning)
                raw=getpass.getpass('ThingSpeak channel Write API Key (hidden): ')
        key=validate_key(raw)
        print('Key format accepted locally; only the server can confirm authorization.')
        entry=upload(t,h,key,'mock' if args.sensor=='mock' else 'hardware')
        print(f'HTTP 200; accepted entry ID: {entry}; temperature {t:.1f} °C; humidity {h:.1f}%. Verify your private channel. Wait at least 20 seconds before another write.')
        return 0
    except (ValueError,RuntimeError,getpass.GetPassWarning,EOFError) as e:
        print('P34:',str(e),file=sys.stderr);return 1

if __name__=='__main__':
    try: sys.exit(main())
    except KeyboardInterrupt: sys.exit(130)
