"""Capture a fictional local traffic graph with Selenium; never logs into Zabbix.

Use a new output directory outside a web root. The fixture-only readiness and
metadata attributes must be replaced for a real, authorized monitoring UI.
"""
from __future__ import annotations
import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import tempfile
from urllib.parse import urlencode
from uuid import uuid4

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options
from selenium.webdriver.edge.service import Service
from selenium.webdriver.support.ui import WebDriverWait


def aware_time(value):
    parsed = datetime.fromisoformat(value)
    if parsed.tzinfo is None:
        raise ValueError('A timezone offset is required')
    return parsed


def capture(args):
    start, end = aware_time(args.from_time), aware_time(args.to_time)
    if end <= start:
        raise ValueError('The end must be after the start')
    fixture = Path(__file__).with_name('fixture.html').resolve(strict=True)
    output = args.output.resolve()
    # Output must be independent of the downloadable sample directory.
    if output == fixture.parent or fixture.parent in output.parents:
        raise ValueError('Choose an output directory outside the sample directory')
    output.mkdir(parents=True, exist_ok=True, mode=0o700)
    expected_period = args.from_time + '/' + args.to_time
    url = fixture.as_uri() + '?' + urlencode({
        'host': 'demo-router', 'from': args.from_time, 'to': args.to_time,
        'scenario': args.scenario,
    })
    options = Options()
    options.add_argument('--headless=new')
    options.add_argument('--window-size=1280,900')
    options.add_argument('--disable-extensions')
    if args.browser_binary:
        options.binary_location = str(args.browser_binary.resolve(strict=True))
    service = Service(executable_path=str(args.driver.resolve(strict=True))) if args.driver else Service()
    driver = None
    # Never reuse a personal browser profile or its cookies/passwords.
    with tempfile.TemporaryDirectory(prefix='graph-profile-', dir=output) as profile:
        options.add_argument('--user-data-dir=' + profile)
        try:
            driver = webdriver.Edge(options=options, service=service)
            driver.set_page_load_timeout(20)
            driver.get(url)

            def graph_ready(browser):
                image = browser.find_element(By.ID, 'traffic-graph')
                if image.get_attribute('data-render-state') != 'ready':
                    return False
                if not image.is_displayed():
                    return False
                loaded = browser.execute_script(
                    'return arguments[0].complete && arguments[0].naturalWidth >= 200 && arguments[0].naturalHeight >= 100;', image)
                return image if loaded else False

            image = WebDriverWait(driver, args.timeout, poll_frequency=0.2).until(graph_ready)
            if image.get_attribute('data-host') != 'demo-router' or image.get_attribute('data-period') != expected_period:
                raise ValueError('The rendered graph does not match the requested host/period')
            png = image.screenshot_as_png
            if not png.startswith(b'\x89PNG\r\n\x1a\n') or len(png) < 1000:
                raise ValueError('The screenshot is not a usable PNG')
            captured = datetime.now(timezone.utc)
            stem = 'demo-traffic-' + captured.strftime('%Y%m%dT%H%M%SZ') + '-' + uuid4().hex[:8]
            # Unique names; a previous successful image is never overwritten.
            image_path, metadata_path = output / (stem + '.png'), output / (stem + '.json')
            with image_path.open('xb') as handle:
                handle.write(png)
            metadata = {'fixture': True, 'host': 'demo-router', 'from': args.from_time, 'to': args.to_time,
                        'capturedAt': captured.isoformat(), 'browserVersion': driver.capabilities.get('browserVersion'),
                        'imageFile': image_path.name, 'imageBytes': len(png)}
            with metadata_path.open('x', encoding='utf-8') as handle:
                json.dump(metadata, handle, ensure_ascii=False, indent=2)
            print(json.dumps({'status': 'captured', **metadata}, ensure_ascii=False))
        finally:
            if driver is not None:
                driver.quit()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--from-time', default='2026-10-01T00:00:00+09:00')
    parser.add_argument('--to-time', default='2026-10-02T00:00:00+09:00')
    parser.add_argument('--scenario', choices=['ready', 'timeout', 'wrong-period', 'broken-image'], default='ready')
    parser.add_argument('--timeout', type=float, default=10)
    parser.add_argument('--driver', type=Path, help='Optional msedgedriver.exe path')
    parser.add_argument('--browser-binary', type=Path, help='Optional msedge.exe path')
    args = parser.parse_args()
    if not 0 < args.timeout <= 60:
        parser.error('timeout must be greater than zero and at most 60 seconds')
    try:
        capture(args)
    except Exception as error:
        # Do not dump a browser profile, cookies, or an arbitrary exception body.
        print(json.dumps({'status': 'failed', 'errorType': type(error).__name__, 'captureComplete': False}))
        return 1
    return 0


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