import json


def count_records_in_s3_csv(bucket: str, s3_file_key: str, s3_client) -> int:
    """
        This function is used to count the number of records found in a CSV on S3 with path
        s3://bucket/s3_file_key .  The number of records is returned.

        This function uses an AWS feature known as "s3 select" which can perform queries
        directly on s3 objects.  This function assumes that the CSVs it is querying have header rows at the top.
    """

    query_result = s3_client.select_object_content(
        Bucket=bucket,
        Key=s3_file_key,
        ExpressionType="SQL",
        Expression="select count(*) as line_count from s3object",
        InputSerialization={
            "CSV": {"FileHeaderInfo": "IGNORE", "AllowQuotedRecordDelimiter": True}
        },
        OutputSerialization={"JSON": {}},
    )
    for event in query_result["Payload"]:
        if "Records" in event:
            json_payload_dict = json.loads(event["Records"]["Payload"].decode("utf-8"))
            return json_payload_dict["line_count"]
    return -1