#!/usr/bin/env python3
"Lite Glue inventory with latest-run times: Python Shell 3.9; raw Cron; one tab-separated CSV."
import argparse
from collections import defaultdict
import csv
from datetime import datetime, timedelta, timezone
from pathlib import Path
import sys
import tempfile
import time
from urllib.parse import unquote, urlsplit

import boto3
from botocore.config import Config
from botocore.exceptions import ClientError, ConnectionError, HTTPClientError

VERSION = "1.0.23"
FILENAME = "glue_job_inventory.csv"
# Seconds to wait before every Glue send; set 2.0 for slower reads. S3 uploads are unaffected.
GLUE_REQUEST_INTERVAL_SECONDS = 1.0
COLUMNS = [
    # Job basics
    "JobName", "Description", "JobType", "GlueVersion",
    "PythonVersion", "JobLanguage", "ScriptLocation", "IAMRole",
    # Job workers, networking and execution limits
    "WorkerType", "NumberOfWorkers", "MaxCapacity", "AutoScaling",
    "Timeout", "MaxRetries", "MaxConcurrentRuns", "Connections",
    # Job libraries and file paths
    "ExtraPyFiles", "ExtraPyFileNames", "ExtraJars", "ExtraJarNames",
    "AdditionalPythonModules", "ExtraFiles", "ExtraFileNames", "TempDir",
    # Job latest-run times
    "LatestJobRunStartedOn", "LatestJobRunCompletedOn", "LatestJobRunDuration",
    # Workflow configuration and latest-run times
    "WorkflowName", "WorkflowDescription", "LatestWorkflowRunStartedOn", "LatestWorkflowRunCompletedOn",
    "WorkflowCurrentLastDuration",
    # Trigger configuration
    "TriggerName", "TriggerType", "TriggerState", "ScheduleCron",
    "PreviousJobs",
    # Inventory warnings
    "InvestigationWarnings",
]
JOB_FIELDS = {
    "Description": "Description", "GlueVersion": "GlueVersion", "Role": "IAMRole",
    "WorkerType": "WorkerType", "NumberOfWorkers": "NumberOfWorkers",
    "MaxCapacity": "MaxCapacity", "Timeout": "Timeout",
    "MaxRetries": "MaxRetries",
}
PARAM_FIELDS = {
    "--extra-py-files": "ExtraPyFiles", "--extra-jars": "ExtraJars",
    "--additional-python-modules": "AdditionalPythonModules", "--extra-files": "ExtraFiles",
    "--job-language": "JobLanguage", "--TempDir": "TempDir", "--enable-auto-scaling": "AutoScaling",
}


# Pace Glue sends, including automatic SDK retries; never inspect or log request contents.
def pace_glue_request(request, **kwargs):
    time.sleep(GLUE_REQUEST_INTERVAL_SECONDS)


# Extract latest-run start/end times; convert Job times to JST and keep Workflow SDK timezones.
# Input: one run, a resource label and a warning callback. Returns: (start text, end text).
def latest_run_times(run, label, warn, job_jst=False):
    if not run:
        warn(label + ": no run history available")
        return "", ""
    values = []
    for field in ("StartedOn", "CompletedOn"):
        value = run.get(field)
        if value is None:
            values.append("")
            state = run.get("JobRunState") or run.get("Status") or "unknown"
            warn("{}: latest run has no {} (status={})".format(label, field, state))
            continue
        # Convert only Job display times, retaining fractional seconds; interpret naive timestamps as UTC.
        if job_jst:
            try:
                if value.tzinfo is None:
                    value = value.replace(tzinfo=timezone.utc)
                value = value.astimezone(timezone(timedelta(hours=9)))
            except (AttributeError, TypeError, ValueError, OverflowError):
                warn(label + ": invalid " + field + "; JST conversion unavailable")
                values.append("")
                continue
        values.append(str(value))
    return tuple(values)


# Format API seconds as x h x m xx s; leave missing values blank and warn on invalid values without estimating.
def format_duration(seconds, warn):
    if seconds is None:
        return ""
    try:
        if isinstance(seconds, bool) or not isinstance(seconds, (int, float)) or seconds < 0:
            raise ValueError("invalid duration")
        total_seconds = int(seconds)
        hours, remainder = divmod(total_seconds, 3600)
        minutes, seconds = divmod(remainder, 60)
        # Omit only leading zero units; keep zero minutes and two-digit seconds after hours. All zero is 00 s.
        if hours:
            return "{} h {} m {:02d} s".format(hours, minutes, seconds)
        if minutes:
            return "{} m {:02d} s".format(minutes, seconds)
        return "{:02d} s".format(seconds)
    except (TypeError, ValueError, OverflowError):
        warn("Run duration unavailable: invalid ExecutionTime or duration")
        return ""


# Read only the latest Job run ExecutionTime; leave missing values blank and format as hours/minutes/seconds.
def job_duration(run, warn):
    return format_duration(run.get("ExecutionTime"), warn)


# Compute the current or final latest Workflow duration as x h x m xx s.
# Use end minus start when finished, or the shared inventory snapshot minus start while RUNNING/STOPPING.
def workflow_duration(run, captured_at, warn):
    started = run.get("StartedOn")
    completed = run.get("CompletedOn")
    if started is None:
        return ""
    if completed is None:
        if run.get("Status") not in ("RUNNING", "STOPPING"):
            return ""
        completed = captured_at
    try:
        # Only normalize calculation copies: interpret naive values as UTC; leave raw timestamp output unchanged.
        if started.tzinfo is None:
            started = started.replace(tzinfo=timezone.utc)
        if completed.tzinfo is None:
            completed = completed.replace(tzinfo=timezone.utc)
        seconds = (completed - started).total_seconds()
        if seconds < 0:
            warn("Workflow duration unavailable: end/snapshot precedes start")
            return ""
        return format_duration(seconds, warn)
    except (AttributeError, TypeError, ValueError, OverflowError):
        warn("Workflow duration unavailable: invalid timestamps")
        return ""


# Record and print deduplicated global warnings to avoid bloating each CSV row.
# Input: warning list and message. No return; print one line without business parameters.
def warn(messages, message):
    if message not in messages:
        messages.append(message)
    print("[WARNING] " + " ".join(message.split()))


# Record API/resource/error identifiers and continue only for service or network failures.
# Input: client, method, warnings and API arguments. Return a response or None.
def read(glue, method, messages, **kwargs):
    # getattr selects the named API method; **kwargs expands request arguments.
    try:
        return getattr(glue, method)(**kwargs)
    except (ClientError, ConnectionError, HTTPClientError) as exc:
        # Prefer AWS Error.Code; use the exception class name for network failures without a response.
        # Let validation and programming errors reach main and stop the inventory.
        response = getattr(exc, "response", {})
        code = type(exc).__name__
        if isinstance(response, dict):
            code = response.get("Error", {}).get("Code", code)
        # GetJob takes JobName; GetWorkflow and GetTrigger take Name.
        # List calls have no single resource name, so log only the API and error code.
        resource_name = kwargs.get("JobName") or kwargs.get("Name")
        if resource_name:
            message = "{} [{}]: {}".format(method, resource_name, code)
        else:
            message = "{}: {}".format(method, code)
        warn(messages, message)
        return None


# Read all name-list pages, including resources behind NextToken.
# Input: method and list field; yield names and retain earlier pages if a later read fails.
def list_all(glue, method, key, messages):
    # Omit NextToken on page one; pass each returned token back until none remains.
    token = None
    seen = set()
    while True:
        # Use the smaller Workflow page size; request up to 100 items for the other lists.
        params = {"MaxResults": 25 if method == "list_workflows" else 100}
        if token:
            params["NextToken"] = token
        response = read(glue, method, messages, **params)
        if response is None:
            return
        # key identifies the names array, e.g. JobNames; yield from returns its items one by one.
        # If a later page fails, previously yielded names remain and messages records the failure.
        yield from response.get(key, [])
        token = response.get("NextToken")
        if not token:
            return
        # Stop on repeated tokens to avoid requesting the same page forever.
        if token in seen:
            warn(messages, method + ": repeated NextToken; enumeration incomplete")
            return
        seen.add(token)


# Collect Job names and build Job-to-Workflow and Job-to-starting-Trigger indexes.
# Input: Glue client. Return Job sets, associations, global/per-Job discovery warnings and metadata caches.
# Actions identify targets and Predicate identifies predecessors; use Graph only for static associations.
def discover(glue):
    # Job names are unique; index keys use exact full names, never substrings or prefixes.
    # workflows maps Job names to sets of Workflow names.
    # trigger_workflows maps Trigger names to sets of Workflow names.
    # by_job maps a Job to the Triggers that start it; a Job can have multiple Triggers.
    messages = []
    # Store resource warnings by exact name and attach details only to related Job rows.
    workflow_warnings = defaultdict(list)
    trigger_warnings = defaultdict(list)
    trigger_jobs = defaultdict(set)
    detail_incomplete = False
    jobs = set()
    triggers = {}
    workflows = defaultdict(set)
    trigger_workflows = defaultdict(set)
    by_job = defaultdict(list)
    workflow_descriptions = {}
    workflow_times = {}
    workflow_durations = {}
    captured_at = datetime.now(timezone.utc)
    # Step 1: read static Workflow Graphs, register memberships and cache Triggers.
    # Deduplicate while preserving order; use node configuration, not embedded run records.
    names = list(dict.fromkeys(list_all(glue, "list_workflows", "Workflows", messages)))
    print("[INFO] Workflows discovered: {}".format(len(names)))
    for index, name in enumerate(names, 1):
        print("[INFO] Processing Workflow {}/{}".format(index, len(names)))
        wf_messages = workflow_warnings[name]
        response = read(glue, "get_workflow", wf_messages, Name=name, IncludeGraph=True)
        workflow = (response or {}).get("Workflow", {})
        # Cache descriptions by Workflow name for exact lookup when building rows.
        workflow_descriptions[name] = workflow.get("Description", "")
        # Reuse LastRun from GetWorkflow; do not enumerate Workflow run history.
        if response and "Workflow" in response:
            workflow_times[name] = latest_run_times(
                workflow.get("LastRun", {}), "Workflow [" + name + "]",
                lambda message: warn(wf_messages, message))
            workflow_durations[name] = workflow_duration(
                workflow.get("LastRun", {}), captured_at,
                lambda message: warn(wf_messages, "Workflow [" + name + "]: " + message))
        if "Graph" not in workflow:
            detail_incomplete = True
            warn(wf_messages, "Workflow graph unavailable [{}]; workflow associations may be incomplete".format(name))
        for node in workflow.get("Graph", {}).get("Nodes", []):
            if node.get("Type") == "JOB" and node.get("Name"):
                jobs.add(node["Name"])
                workflows[node["Name"]].add(name)
            elif node.get("Type") == "TRIGGER":
                trigger = node.get("TriggerDetails", {}).get("Trigger") or {"Name": node.get("Name")}
                if trigger.get("Name"):
                    # Keep one cached Trigger per name and accumulate memberships separately.
                    triggers.setdefault(trigger["Name"], trigger)
                    trigger_workflows[trigger["Name"]].add(name)
    # Step 2: list regional Jobs and Triggers, including resources outside Workflows.
    jobs.update(list_all(glue, "list_jobs", "JobNames", messages))
    for name in list_all(glue, "list_triggers", "TriggerNames", messages):
        triggers.setdefault(name, {"Name": name})
    # Step 3: read each Trigger and index it under its target Jobs.
    for name in sorted(triggers):
        tr_messages = trigger_warnings[name]
        response = read(glue, "get_trigger", tr_messages, Name=name)
        if response is None:
            detail_incomplete = True
        # Fall back to the Graph cache if GetTrigger fails, retaining the read-failure warning.
        trigger = (response or {}).get("Trigger") or triggers[name]
        if trigger.get("WorkflowName"):
            trigger_workflows[name].add(trigger["WorkflowName"])
        if "Type" not in trigger or "Actions" not in trigger:
            detail_incomplete = True
            warn(tr_messages, "Trigger details unavailable: " + name)
        # Actions means which Job to start, not a prerequisite; omit Crawler targets from Job rows.
        # Deduplicate target names so repeated Actions do not add the same Trigger twice.
        targets = {a["JobName"] for a in trigger.get("Actions", []) if a.get("JobName")}
        for job in targets:
            jobs.add(job)
            trigger_jobs[name].add(job)
            workflows[job].update(trigger_workflows[name])
            detail = {}
            for key in ("Type", "State", "Schedule", "Predicate"):
                if key in trigger:
                    detail[key] = trigger[key]
            detail["Name"] = name
            by_job[job].append(detail)
        # Predicate means which prerequisite must satisfy a condition. Include predecessor Jobs in discovery,
        # but do not register this Trigger as starting those predecessor Jobs in by_job.
        for condition in trigger.get("Predicate", {}).get("Conditions", []):
            if condition.get("JobName"):
                jobs.add(condition["JobName"])
                trigger_jobs[name].add(condition["JobName"])
                workflows[condition["JobName"]].update(trigger_workflows[name])
    # Fetch metadata for Workflows discovered later through Triggers by exact name, once per name, independently of initial list coverage.
    referenced = {wf for memberships in workflows.values() for wf in memberships}
    for name in sorted(referenced - set(workflow_descriptions)):
        wf_messages = workflow_warnings[name]
        response = read(glue, "get_workflow", wf_messages, Name=name, IncludeGraph=False)
        workflow = (response or {}).get("Workflow", {})
        if not workflow:
            detail_incomplete = True
            warn(wf_messages, "Workflow [" + name + "]: metadata unavailable; name obtained from Trigger")
            continue
        # Fill description and latest-run caches without changing the established associations from a new Graph.
        workflow_descriptions[name] = workflow.get("Description", "")
        workflow_times[name] = latest_run_times(
            workflow.get("LastRun", {}), "Workflow [" + name + "]",
            lambda message: warn(wf_messages, message))
        workflow_durations[name] = workflow_duration(
            workflow.get("LastRun", {}), captured_at,
            lambda message: warn(wf_messages, "Workflow [" + name + "]: " + message))
    discovery_warnings = defaultdict(list)
    for job, memberships in workflows.items():
        for wf in sorted(memberships):
            discovery_warnings[job].extend(workflow_warnings[wf])
    for trigger, related_jobs in trigger_jobs.items():
        for job in related_jobs:
            discovery_warnings[job].extend(trigger_warnings[trigger])
    if detail_incomplete:
        warn(messages, "Workflow/Trigger discovery incomplete; associations may be incomplete; see resource warnings in run log")
    print("[INFO] Jobs discovered: {}; Triggers discovered: {}".format(len(jobs), len(triggers)))
    return jobs, workflows, by_job, messages, workflow_descriptions, workflow_times, workflow_durations, discovery_warnings


# Extract filenames from comma-separated paths; parse URL paths without downloading.
# Input: library path text. Return comma-separated filenames.
def filenames(paths):
    names = []
    for path in str(paths).split(","):
        path = path.strip()
        if path:
            # Use only the URL path, omit query parameters, and decode %xx with unquote.
            # Keep full paths in their original columns; filenames are derived for easier review.
            url_path = unquote(urlsplit(path).path)
            names.append(url_path.rsplit("/", 1)[-1])
    return ",".join(names)


# Build one row from Job configuration, Workflow membership and starting Triggers; no API calls.
# Input: cached configuration and associations. Return fixed fields with raw Cron unchanged.
# NonOverridable parameters win in dedicated columns; omit full parameter and Trigger JSON.
def make_row(name, job, memberships, triggers, messages, workflow_descriptions, workflow_times, workflow_durations):
    # Initialize blank columns, then fill available values; do not invent zero or discard actual 0/False.
    row = {c: "" for c in COLUMNS}
    row["JobName"] = name
    row.update({column: job.get(key, "") for key, column in JOB_FIELDS.items()})
    # Read only bound connection names from the Job, never GetConnection or credentials.
    # Join multiple connections with commas in their original order; absent configuration is blank.
    row["Connections"] = ",".join(job.get("Connections", {}).get("Connections", []))
    command = job.get("Command", {})
    job_types = {
        "glueetl": "Spark",
        "gluestreaming": "Spark Streaming",
        "pythonshell": "Python Shell",
        "glueray": "Ray",
    }
    command_name = command.get("Name", "")
    row["JobType"] = job_types.get(command_name, command_name)
    row["PythonVersion"] = command.get("PythonVersion", "")
    row["ScriptLocation"] = command.get("ScriptLocation", "")
    row["MaxConcurrentRuns"] = job.get("ExecutionProperty", {}).get("MaxConcurrentRuns", "")
    defaults = job.get("DefaultArguments", {})
    locked = job.get("NonOverridableArguments", {})
    # Later dictionaries win: NonOverridableArguments overrides same-name DefaultArguments.
    # This selects static Job values, not the effective runtime arguments including Trigger overrides.
    selected = {**defaults, **locked}
    row.update({column: selected.get(key, "") for key, column in PARAM_FIELDS.items()})
    library_fields = (
        ("ExtraPyFiles", "ExtraPyFileNames"),
        ("ExtraJars", "ExtraJarNames"),
        ("ExtraFiles", "ExtraFileNames"),
    )
    for source, target in library_fields:
        row[target] = filenames(row[source]) if row[source] else ""
    if len(memberships) == 1:
        row["WorkflowName"] = next(iter(memberships))
        # Leave absent, ambiguous or unavailable Workflow descriptions blank; never substitute Job.Description.
        row["WorkflowDescription"] = workflow_descriptions.get(row["WorkflowName"], "")
        if row["WorkflowName"] in workflow_descriptions and not row["WorkflowDescription"]:
            messages.append("Workflow [" + row["WorkflowName"] + "]: Description empty or absent in GetWorkflow response")
        started, completed = workflow_times.get(row["WorkflowName"], ("", ""))
        row["LatestWorkflowRunStartedOn"] = started
        row["LatestWorkflowRunCompletedOn"] = completed
        row["WorkflowCurrentLastDuration"] = workflow_durations.get(row["WorkflowName"], "")
    elif len(memberships) > 1:
        # Never pick an arbitrary Workflow for a scalar field; list all names in the warning.
        messages.append("Multiple workflows: " + ", ".join(sorted(memberships)))
    # Fill scalar Trigger fields only for a unique Trigger; this variant has no full Trigger JSON.
    if len(triggers) == 1:
        trigger = triggers[0]
        row["TriggerName"] = trigger["Name"]
        row["TriggerType"] = trigger.get("Type", "")
        row["TriggerState"] = trigger.get("State", "")
        if trigger.get("Type") == "SCHEDULED":
            row["ScheduleCron"] = trigger.get("Schedule", "")
        elif trigger.get("Type") == "CONDITIONAL":
            # PreviousJobs contains only Job names; omit states, AND/ANY and Crawler conditions here.
            # Keep original order and duplicates; names alone cannot reconstruct the full predicate.
            conditions = trigger.get("Predicate", {}).get("Conditions", [])
            previous_jobs = [c["JobName"] for c in conditions if c.get("JobName")]
            row["PreviousJobs"] = ",".join(previous_jobs)
    elif len(triggers) > 1:
        # Do not combine different Triggers' schedules and predicates into one misleading rule.
        messages.append("Multiple triggers: " + ", ".join(t["Name"] for t in triggers)
                        + "; scalar trigger fields blank; details not exported")
    row["InvestigationWarnings"] = " | ".join(dict.fromkeys(messages))
    return row


# Discover resources, GetJob and build rows; query each unique Job definition once.
# Return rows; keep a Job name and warning even if its definition cannot be read.
def collect(glue):
    jobs, workflows, triggers, common, workflow_descriptions, workflow_times, workflow_durations, discovery_warnings = discover(glue)
    rows = []
    for index, name in enumerate(sorted(jobs), 1):
        print("[INFO] Processing Job {}/{}".format(index, len(jobs)))
        # Merge global and current-Job discovery warnings without copying other Workflows' errors.
        messages = list(common) + discovery_warnings[name]
        response = read(glue, "get_job", messages, JobName=name)
        job = (response or {}).get("Job", {})
        if not job:
            warn(messages, "Job details unavailable: " + name)
        # Keep names and associations for recoverable reads; let row-conversion bugs terminate the run.
        # GetJobRuns returns newest first; use only the first run, without falling back to a completed older run.
        response = read(glue, "get_job_runs", messages, JobName=name, MaxResults=1)
        started, completed = "", ""
        duration = ""
        if response is not None:
            runs = response.get("JobRuns", [])
            run = runs[0] if runs else {}
            started, completed = latest_run_times(
                run, "Job [" + name + "]",
                lambda message: warn(messages, message), job_jst=True)
            duration = job_duration(
                run,
                lambda message: warn(messages, "Job [" + name + "]: " + message))
        row = make_row(name, job, workflows[name], triggers[name], messages, workflow_descriptions, workflow_times, workflow_durations)
        row["LatestJobRunStartedOn"] = started
        row["LatestJobRunCompletedOn"] = completed
        row["LatestJobRunDuration"] = duration
        rows.append(row)
    if not rows:
        # Zero rows plus discovery warnings cannot prove an empty account; do not upload an empty replacement.
        # Allow partial output when rows exist; accept zero rows only after warning-free discovery.
        if common:
            warn(common, "No jobs discovered and discovery has warnings; upload cancelled to preserve the existing result")
            raise RuntimeError("Discovery incomplete; empty result must not be uploaded")
        print("[INFO] Discovery completed successfully; no jobs found")
    return rows


# Write one UTF-8-SIG, tab-separated CSV with JobName first.
# Prefix formula-risk values with an apostrophe and warn about long values without truncation.
def write_csv(path, rows):
    # BOM helps detect encoding; newline='' lets csv manage line endings.
    # DictWriter handles tabs, line breaks and quotes; never join cell values manually.
    with open(path, "w", encoding="utf-8-sig", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=COLUMNS, delimiter="\t", lineterminator="\n")
        writer.writeheader()
        for row in rows:
            safe = {}
            notices = []
            for column in COLUMNS:
                value = row.get(column, "")
                # CSV is text: None becomes blank, booleans become lowercase, and numeric zero is preserved.
                if value is None:
                    value = ""
                elif isinstance(value, bool):
                    value = str(value).lower()
                else:
                    value = str(value)
                # Keep the agreed Excel protection and record the protected column names.
                # lstrip is for checking only; preserve whitespace, but note the apostrophe changes the CSV value.
                if value.startswith(("\t", "\r", "\n")) or value.lstrip().startswith(("=", "+", "-", "@")):
                    value = "'" + value
                    notices.append("Excel safety prefix: " + column)
                # Do not truncate long values; retain the full CSV text and warn about Excel's cell limit.
                if len(value) > 32767:
                    notices.append("Excel cell limit exceeded: " + column)
                safe[column] = value
            all_notices = [safe["InvestigationWarnings"]] + notices
            safe["InvestigationWarnings"] = " | ".join(filter(None, all_notices))
            writer.writerow(safe)


# Resolve the output prefix and use this run's timestamped filename.
# Input: S3 prefix or legacy file URI and this run's filename. Return Bucket and Key.
def destination(uri, filename):
    # Split s3://bucket/reports/ into bucket and reports/; reject queries and fragments.
    parsed = urlsplit(uri)
    if parsed.scheme != "s3" or not parsed.netloc or parsed.query or parsed.fragment:
        raise ValueError("Use s3://bucket/prefix/ for OUTPUT_S3_URI")
    key = parsed.path.lstrip("/")
    # Accept legacy glue_job_inventory.csv URIs but replace the basename with this run's timestamped name.
    if key == FILENAME or key.endswith("/" + FILENAME):
        prefix = key[:-len(FILENAME)]
        return parsed.netloc, prefix + filename
    if key.lower().endswith((".csv", ".tsv", ".json")):
        raise ValueError("Output filename must be " + FILENAME)
    prefix = key.rstrip("/") + "/" if key else ""
    return parsed.netloc, prefix + filename


# Read two arguments, collect configuration, write CSV and upload one result object.
# Return 0 when the workflow finishes (inspect warnings) or 1 on runtime/upload failure.
def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
    parser.add_argument("--OUTPUT_S3_URI", required=True)
    parser.add_argument("--REGION", default="ap-northeast-1")
    # Ignore Glue-injected arguments not recognized by this script.
    args = parser.parse_known_args(argv)[0]
    try:
        # Explicitly use JST (UTC+9), independent of the Glue host and queried Region.
        # Generate the timestamp once at startup so local and S3 filenames stay consistent.
        started_at = datetime.now(timezone(timedelta(hours=9)))
        filename = started_at.strftime("%Y%m%d_%H%M%S_") + FILENAME
        bucket, key = destination(args.OUTPUT_S3_URI, filename)
        config = Config(
            connect_timeout=5,
            read_timeout=30,
            retries={"mode": "standard", "total_max_attempts": 4},
        )
        # Use default runtime credentials; do not accept keys or switch Roles.
        session = boto3.session.Session()
        print("[INFO] Lite with runs version: {}; Region: {}".format(VERSION, args.REGION))
        glue_config = Config(connect_timeout=5, read_timeout=30,
                             retries={"mode": "standard", "total_max_attempts": 8})
        glue = session.client("glue", region_name=args.REGION, config=glue_config)
        glue.meta.events.register("before-send.glue", pace_glue_request)
        print("[INFO] Glue pacing: {} seconds before each send; SDK attempts up to 8".format(GLUE_REQUEST_INTERVAL_SECONDS))
        rows = collect(glue)
        # Only write/upload after collection returns; clean up the temporary directory on exit.
        # PutObject runs once; same-second runs to the same prefix can still collide.
        with tempfile.TemporaryDirectory(prefix="glue-lite-") as directory:
            path = Path(directory) / filename
            write_csv(path, rows)
            with path.open("rb") as body:
                s3 = session.client("s3", region_name=args.REGION, config=config)
                s3.put_object(
                    Bucket=bucket,
                    Key=key,
                    Body=body,
                    ContentType="text/tab-separated-values; charset=utf-8",
                )
        print("[INFO] Output: s3://{}/{}".format(bucket, key))
        print("[INFO] Export completed: {} jobs; inspect InvestigationWarnings".format(len(rows)))
        return 0
    except Exception as exc:
        # The outer boundary returns failure and ends the job; unlike read, it never continues after this error.
        # Print only error codes or exception classes, not full AWS responses or business parameters.
        response = getattr(exc, "response", {})
        code = type(exc).__name__
        if isinstance(response, dict):
            code = response.get("Error", {}).get("Code", code)
        print("[ERROR] " + str(code))
        return 1


if __name__ == "__main__":
    sys.exit(main())
