"""Command-line entry point for exploration and production polling.""" from __future__ import annotations import argparse import json import os import sys from collections.abc import Sequence from pathlib import Path from production_analytics.enlyze.exploration import ( ExplorationClient, ExplorationError, ExplorationSettings, load_secret_file, ) from production_analytics.enlyze.sanitize import sanitize def _query_item(value: str) -> tuple[str, str]: if "=" not in value: raise argparse.ArgumentTypeError("query parameters must use KEY=VALUE format") key, item_value = value.split("=", 1) if not key: raise argparse.ArgumentTypeError("query parameter key must not be empty") return key, item_value def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="production-analytics") namespaces = parser.add_subparsers(dest="namespace", required=True) enlyze = namespaces.add_parser("enlyze", help="Read-only ENLYZE API exploration") commands = enlyze.add_subparsers(dest="command", required=True) raw = commands.add_parser("raw", help="GET an operator-verified relative API path") raw.add_argument("path", help="Relative API path beginning with '/'") raw.add_argument("--query", action="append", type=_query_item, default=[], metavar="KEY=VALUE") raw.add_argument("--pretty", action="store_true", help="Pretty-print sanitized JSON") raw.add_argument("--verbose", action="store_true", help="Show safe request progress on stderr") raw.add_argument( "--save-fixture", metavar="NAME", help="Save sanitized JSON under fixtures/enlyze/" ) raw.add_argument( "--save-raw", metavar="NAME", help="Save unmodified response under ignored data/raw/enlyze/" ) raw.add_argument( "--fixture-dir", type=Path, default=Path("fixtures/enlyze"), help=argparse.SUPPRESS ) raw.add_argument( "--raw-dir", type=Path, default=Path("data/raw/enlyze"), help=argparse.SUPPRESS ) raw.add_argument( "--secrets-file", type=Path, default=Path("secrets/enlyze.env"), help="Local dotenv-style secret file (default: secrets/enlyze.env)", ) timeseries = commands.add_parser("timeseries", help="Read-only POST /v2/timeseries exploration") timeseries.add_argument("--machine", required=True, help="Machine UUID") timeseries.add_argument("--start", required=True, help="ISO 8601 datetime with timezone") timeseries.add_argument("--end", required=True, help="ISO 8601 datetime with timezone") timeseries.add_argument("--variable", required=True, help="Variable UUID") timeseries.add_argument( "--resampling-interval", type=int, help="Seconds; schema range is 10..604800" ) timeseries.add_argument( "--resampling-method", choices=[ "first", "last", "max", "min", "count", "sum", "avg", "median", "std", "q5", "q25", "q75", "q95", ], help="Optional schema-defined method for this variable", ) timeseries.add_argument("--pretty", action="store_true", help="Pretty-print sanitized JSON") timeseries.add_argument( "--verbose", action="store_true", help="Show safe request progress on stderr" ) timeseries.add_argument( "--save-fixture", metavar="NAME", help="Save sanitized JSON under fixtures/enlyze/" ) timeseries.add_argument( "--save-raw", metavar="NAME", help="Save unmodified response under ignored data/raw/enlyze/" ) timeseries.add_argument( "--fixture-dir", type=Path, default=Path("fixtures/enlyze"), help=argparse.SUPPRESS ) timeseries.add_argument( "--raw-dir", type=Path, default=Path("data/raw/enlyze"), help=argparse.SUPPRESS ) timeseries.add_argument( "--secrets-file", type=Path, default=Path("secrets/enlyze.env"), help="Local dotenv-style secret file (default: secrets/enlyze.env)", ) historical = namespaces.add_parser("historical-reconcile", help="Repair historical attribution") historical.add_argument("--lookback-days", type=int, default=3) historical.add_argument("--dry-run", action="store_true") historical.add_argument("--verbose", action="store_true", help="Show individual record diagnostics as well as summaries") historical.add_argument("--config", type=Path, default=Path("config/shift-report-machines.yaml")) historical.add_argument("--order-formats", type=Path, default=Path("config/historical-order-formats.yaml")) historical.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env")) historical.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env")) historical.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env")) run = namespaces.add_parser("run", help="Foreground production runners") runners = run.add_subparsers(dest="command", required=True) material = runners.add_parser("material-poll", help="Continuously poll material consumption") material.add_argument("--config", type=Path, required=True) material.add_argument("--calculation-id") material.add_argument("--poll-interval-seconds", type=float, default=10.0) material.add_argument("--state-directory", type=Path, default=Path("data/state/material")) material.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env")) material.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env")) power = runners.add_parser( "power-meter", help="Collect configured ENLYZE power-meter telemetry", ) power.add_argument("--config", type=Path, required=True) power.add_argument("--meter") power.add_argument("--start", help="ISO timestamp; defaults to one polling window ago") power.add_argument("--end", help="ISO timestamp; defaults to now") power.add_argument("--follow", action="store_true", help="Keep polling until interrupted") power.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env")) power.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env")) report = namespaces.add_parser("report", help="Generate independent reports") report_commands = report.add_subparsers(dest="command", required=True) monthly = report_commands.add_parser("monthly", help="Render one configured monthly PDF") monthly.add_argument("--config", type=Path, required=True) monthly.add_argument("--meter") monthly.add_argument("--month", required=True, help="YYYY-MM") monthly.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env")) shift = report_commands.add_parser("shift", help="Render one explicit shift report PDF") shift.add_argument("--config", type=Path, default=Path("config/shift-report-machines.yaml")) shift.add_argument("--machine", required=True) shift.add_argument("--start", required=True, help="ISO 8601 datetime with timezone") shift.add_argument("--end", required=True, help="ISO 8601 datetime with timezone") shift.add_argument("--output", type=Path, required=True) shift.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env")) shift.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env")) shift.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env")) channel_material = runners.add_parser( "channel-material-poll", help="Continuously poll channel-level material consumption" ) channel_material.add_argument("--config", type=Path, required=True) channel_material.add_argument("--poll-interval-seconds", type=float, default=10.0) channel_material.add_argument( "--state-directory", type=Path, default=Path("data/state/channel-material") ) channel_material.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env")) channel_material.add_argument("--once", action="store_true", help="Run one poll cycle and exit") efficiency = runners.add_parser("material-efficiency", help="Persist ERP feedback KPI points") efficiency.add_argument("--config", type=Path, required=True) efficiency.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env")) efficiency.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env")) downtime = runners.add_parser("downtime-reconcile", help="Reconcile ENLYZE downtime events") downtime.add_argument("--config", type=Path, required=True) downtime.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env")) downtime.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env")) return parser def _write_fixture(directory: Path, name: str, payload: object) -> Path: candidate = Path(name) if candidate.name != name or candidate.suffix.lower() != ".json": raise ExplorationError("Fixture name must be a plain filename ending in .json.") directory.mkdir(parents=True, exist_ok=True) destination = directory / candidate destination.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") return destination def _run_material(args: argparse.Namespace) -> int: from production_analytics.calculations.config import ( CalculationConfigError, load_material_calculation, ) from production_analytics.enlyze.exploration import ConfigurationError from production_analytics.service.material_runtime import build_material_runner try: calculation = load_material_calculation(args.config, args.calculation_id) runner = build_material_runner( calculation, poll_interval_seconds=args.poll_interval_seconds, state_directory=args.state_directory, erp_secrets_file=args.erp_secrets_file, secrets_file=args.secrets_file, ) runner.run() except (CalculationConfigError, ConfigurationError) as exc: print(f"Config/startup error: {exc}", file=sys.stderr) return 2 except Exception as exc: print(f"Startup/runtime error: {type(exc).__name__}", file=sys.stderr) return 1 except KeyboardInterrupt: return 0 return 0 def _run_channel_material(args: argparse.Namespace) -> int: from production_analytics.calculations.channel_config import load_channel_material_calculation from production_analytics.calculations.config import CalculationConfigError from production_analytics.enlyze.exploration import ConfigurationError from production_analytics.service.channel_material_runtime import build_channel_material_runner try: calculation = load_channel_material_calculation(args.config) runner = build_channel_material_runner( calculation, poll_interval_seconds=args.poll_interval_seconds, state_directory=args.state_directory, secrets_file=args.secrets_file, ) if args.once: runner.run_once() else: runner.run() except (CalculationConfigError, ConfigurationError) as exc: print(f"Config/startup error: {exc}", file=sys.stderr) return 2 except KeyboardInterrupt: return 0 except Exception as exc: print(f"Startup/runtime error: {type(exc).__name__}", file=sys.stderr) return 1 return 0 def _run_material_efficiency(args: argparse.Namespace) -> int: from production_analytics.calculations.config import CalculationConfigError from production_analytics.enlyze.exploration import ConfigurationError from production_analytics.service.material_efficiency_runtime import ( build_material_efficiency_runner, ) try: build_material_efficiency_runner( args.config, secrets_file=args.secrets_file, erp_secrets_file=args.erp_secrets_file, ).run() except (CalculationConfigError, ConfigurationError) as exc: print(f"Config/startup error: {exc}", file=sys.stderr) return 2 except Exception as exc: print(f"Startup/runtime error: {type(exc).__name__}", file=sys.stderr) return 1 except KeyboardInterrupt: return 0 return 0 def _runtime_environment(*paths: Path) -> dict[str, str]: environment = dict(os.environ) for path in paths: environment.update(load_secret_file(path)) return environment def _parse_cli_timestamp(value: str) -> object: from datetime import datetime parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) if parsed.tzinfo is None: raise ExplorationError("timestamps must include a timezone") return parsed def _run_power_meter(args: argparse.Namespace) -> int: import time from datetime import UTC, datetime, timedelta from production_analytics.calculations.config import CalculationConfigError from production_analytics.enlyze.exploration import ConfigurationError from production_analytics.power_meter.config import load_power_meter_config from production_analytics.power_meter.gateway import PowerMeterGateway from production_analytics.power_meter.repository import PostgresPowerMeterRepository from production_analytics.power_meter.runtime import PowerMeterCollector try: config = load_power_meter_config(args.config, args.meter) environment = _runtime_environment(args.secrets_file, args.db_secrets_file) settings = ExplorationSettings.from_environment(environment) from production_analytics.service.postgres_material import PostgresSettings db = PostgresSettings.from_environment(environment) collector = PowerMeterCollector(config, PowerMeterGateway(ExplorationClient(settings)), PostgresPowerMeterRepository(db)) if args.follow: while True: count = collector.poll_once() print(f"Collected {count} {config.name} power-meter readings.", flush=True) time.sleep(config.poll_interval_seconds) now = datetime.now(UTC) end = _parse_cli_timestamp(args.end) if args.end else now start = (_parse_cli_timestamp(args.start) if args.start else end - timedelta(seconds=config.poll_interval_seconds * 2)) count = collector.backfill(start, end) print(f"Collected {count} {config.name} power-meter readings.") return 0 except (CalculationConfigError, ConfigurationError, ExplorationError, ValueError) as exc: print(f"Config/startup error: {exc}", file=sys.stderr) return 2 def _run_monthly_report(args: argparse.Namespace) -> int: from production_analytics.calculations.config import CalculationConfigError from production_analytics.enlyze.exploration import ConfigurationError from production_analytics.power_meter.config import load_power_meter_config from production_analytics.power_meter.repository import PostgresPowerMeterRepository from production_analytics.power_meter.runtime import monthly_report try: config = load_power_meter_config(args.config, args.meter) environment = _runtime_environment(args.db_secrets_file) from production_analytics.service.postgres_material import PostgresSettings repository = PostgresPowerMeterRepository(PostgresSettings.from_environment(environment)) path = monthly_report(config, repository, args.month) print(path) return 0 except (CalculationConfigError, ConfigurationError, ValueError, RuntimeError) as exc: print(f"Report error: {exc}", file=sys.stderr) return 2 def _run_shift_report(args: argparse.Namespace) -> int: from production_analytics.calculations.shift_speed import validate_speed_window from production_analytics.enlyze.exploration import ConfigurationError from production_analytics.presentation.shift_report import write_pdf from production_analytics.service.shift_report_config import load_shift_report_machines from production_analytics.service.shift_report_runtime import build_shift_report_service try: start = _parse_cli_timestamp(args.start) end = _parse_cli_timestamp(args.end) validate_speed_window(start, end) machines = load_shift_report_machines(args.config) if args.machine not in machines: raise ValueError(f"Unknown shift-report machine: {args.machine}") environment = _runtime_environment( args.secrets_file, args.erp_secrets_file, args.db_secrets_file, ) service = build_shift_report_service(machines, environment) report = service.build(machine_name=args.machine, start=start, end=end) write_pdf(report, args.output) except (ValueError, ConfigurationError, ExplorationError) as exc: print(f"Report error: {exc}", file=sys.stderr) return 2 except Exception as exc: print(f"Report failed: {type(exc).__name__}", file=sys.stderr) return 1 print(args.output) return 0 def _run_downtime(args: argparse.Namespace) -> int: from production_analytics.service.downtime_runtime import build_downtime_runner try: build_downtime_runner( args.config, secrets_file=args.secrets_file, erp_secrets_file=args.erp_secrets_file, ).run() except Exception as exc: print(f"Config/startup/runtime error: {type(exc).__name__}", file=sys.stderr) return 1 return 0 def main(argv: Sequence[str] | None = None) -> int: args = _parser().parse_args(argv) if args.namespace == "historical-reconcile": from production_analytics.service.historical_runtime import run try: return run(args, _runtime_environment( args.secrets_file, args.erp_secrets_file, args.db_secrets_file, )) except Exception as exc: print(f"Historical reconciliation failed: {type(exc).__name__}: {exc}", file=sys.stderr) return 1 if args.namespace == "run": if args.command == "channel-material-poll": return _run_channel_material(args) if args.command == "material-efficiency": return _run_material_efficiency(args) if args.command == "power-meter": return _run_power_meter(args) if args.command == "downtime-reconcile": return _run_downtime(args) return _run_material(args) if args.namespace == "report": if args.command == "shift": return _run_shift_report(args) return _run_monthly_report(args) if args.namespace != "enlyze" or args.command not in {"raw", "timeseries"}: return 2 try: environment = dict(os.environ) environment.update(load_secret_file(args.secrets_file)) settings = ExplorationSettings.from_environment(environment) if args.verbose: authentication = "configured" if settings.api_key else "not configured" operation = "GET" if args.command == "raw" else "POST" target = args.path if args.command == "raw" else "/v2/timeseries" print( f"Requesting {operation} {target} (timeout={settings.timeout_seconds:g}s; " f"authentication {authentication}).", file=sys.stderr, ) client = ExplorationClient(settings) if args.command == "raw": query = dict(args.query) if args.path == "/v2/variables": pages = client.get_all_pages(args.path, query) response = pages[0] if len(pages) > 1: merged = dict(response.body) merged["data"] = [item for page in pages for item in page.body.get("data", [])] merged["metadata"] = {"next_cursor": None, "pages": len(pages)} response = type(response)(response.status_code, response.path, response.headers, merged) else: response = client.get(args.path, query) request = {"method": "GET", "path": response.path} else: if ( args.resampling_interval is not None and not 10 <= args.resampling_interval <= 604800 ): raise ExplorationError( "--resampling-interval must be between 10 and 604800 seconds." ) variable: dict[str, str] = {"uuid": args.variable} if args.resampling_method: variable["resampling_method"] = args.resampling_method request_body: dict[str, object] = { "machine": args.machine, "start": args.start, "end": args.end, "variables": [variable], } if args.resampling_interval is not None: request_body["resampling_interval"] = args.resampling_interval response = client.post_json("/v2/timeseries", request_body) request = {"method": "POST", "path": response.path, "body": request_body} if args.verbose: print(f"Received HTTP {response.status_code} for {response.path}.", file=sys.stderr) raw_payload = { "request": request, "response": { "status_code": response.status_code, "headers": response.headers, "body": response.body, }, } payload = sanitize(raw_payload) indent = 2 if args.pretty or args.save_fixture else None print(json.dumps(payload, indent=indent, sort_keys=True)) if args.save_fixture: print( "Sanitized fixture written to " f"{_write_fixture(args.fixture_dir, args.save_fixture, payload)}" ) if args.save_raw: print( "Raw response written to " f"{_write_fixture(args.raw_dir, args.save_raw, raw_payload)}" ) except ExplorationError as error: print(f"ENLYZE exploration error: {error}") return 1 return 0 if __name__ == "__main__": raise SystemExit(main())