#!/usr/bin/env python3
"""
Generates Part A of "Self-Managed IO River Security in Akamai": creates the
IOR-Security Include via Akamai's Property Manager API (PAPI), defines its
variables, and builds the IORiver-Variables + IORiver-Security +
IORiver-Security-Cleared rule tree. See
docs/docs/Guides/Security/Self-Managed IO River Security in Akamai.md for the
manual, click-through version of these steps.

Requires Akamai API credentials in ~/.edgerc (see https://techdocs.akamai.com/developer/docs/set-up-authentication-credentials)
and the `edgegrid-python` package (pip install -r requirements.txt).
"""

import argparse
import json
import sys
from pathlib import Path

import requests
from akamai.edgegrid import EdgeGridAuth, EdgeRc

INCLUDE_NAME = "IOR-Security"
# productId required by PAPI to create an Include; update to match your contract's catalog.
PRODUCT_ID = "prd_Alta"

# (variable name, description) - mirrors Part A, Step 2 of the guide
VARIABLES = [
    ("IORIVER_CLEARED", "Extracted from the X-IOR-Cleared request header to detect already-cleared requests."),
    ("IORIVER_ASN", "EdgeScape AS number, forwarded to the security layer."),
    ("IORIVER_CITY", "EdgeScape city, forwarded to the security layer."),
    ("IORIVER_COUNTRY", "EdgeScape country code, forwarded to the security layer."),
    ("IORIVER_REGION", "EdgeScape region code, forwarded to the security layer."),
    ("IORIVER_CLIENT_IP", "Extracted from the X-IOR-Client-IP request header; the original client IP once the security layer clears the request."),
]


def parse_args():
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser(description="Create the IOR-Security Include in Akamai Property Manager.")
    parser.add_argument(
        "--edgerc", type=Path, default=Path("~/.edgerc").expanduser(), help="Path to .edgerc credentials file (default: ~/.edgerc)"
    )
    parser.add_argument("--contract-id", required=True, help="Contract ID, e.g. ctr_1-ABC123")
    parser.add_argument("--group-id", required=True, help="Group ID, e.g. grp_12345")
    parser.add_argument(
        "--rule-format", help="Rule format to pin the new Include to (default: account's current latest)")
    parser.add_argument("--dry-run", action="store_true",
                        help="Print the generated rule tree JSON and exit, without calling the Akamai API")
    return parser.parse_args()


def numeric_id(prefixed_id):
    """Strip an Akamai ID prefix (e.g. 'inc_') to get the raw numeric suffix."""
    return prefixed_id.split("_", 1)[-1]


def check_response(resp):
    """Raise for HTTP errors, printing Akamai's problem+json error body first."""
    try:
        resp.raise_for_status()
    except requests.exceptions.HTTPError:
        print(f"Akamai API error {resp.status_code} for {resp.request.method} {resp.request.url}:", file=sys.stderr)
        print(resp.text, file=sys.stderr)
        raise


def build_rule_tree(include_numeric_id):
    """Build the Part A rule tree: IORiver-Variables + IORiver-Security child rules."""
    prefix = f"PMINC{include_numeric_id}_"

    def var_name(name):
        return f"{prefix}{name}"

    variables = [
        {"name": var_name(name), "value": "", "description": description, "hidden": True, "sensitive": False}
        for name, description in VARIABLES
    ]

    def set_variable_from_edgescape(variable_name, location_id):
        return {
            "name": "setVariable",
            "options": {
                "valueSource": "EXTRACT",
                "transform": "NONE",
                "variableName": var_name(variable_name),
                "extractLocation": "EDGESCAPE",
                "locationId": location_id,
            },
        }

    def add_header(header_name, header_value):
        return {
            "name": "modifyOutgoingRequestHeader",
            "options": {
                "action": "ADD",
                "standardAddHeaderName": "OTHER",
                "customHeaderName": header_name,
                "headerValue": header_value,
            },
        }

    iorriver_variables_rule = {
        "name": "IORiver-Variables",
        "criteria": [],
        "criteriaMustSatisfy": "all",
        "behaviors": [
            {
                "name": "setVariable",
                "options": {
                    "valueSource": "EXTRACT",
                    "transform": "NONE",
                    "variableName": var_name("IORIVER_CLEARED"),
                    "extractLocation": "CLIENT_REQUEST_HEADER",
                    "headerName": "X-IOR-Cleared",
                },
            },
            {
                "name": "setVariable",
                "options": {
                    "valueSource": "EXTRACT",
                    "transform": "NONE",
                    "variableName": var_name("IORIVER_CLIENT_IP"),
                    "extractLocation": "CLIENT_REQUEST_HEADER",
                    "headerName": "X-IOR-Client-IP",
                },
            },
        ],
        "children": [],
    }

    iorriver_security_rule = {
        "name": "IORiver-Security",
        "criteria": [
            {
                "name": "matchVariable",
                "options": {
                    "matchOperator": "IS_NOT",
                    "matchWildcard": False,
                    "matchCaseSensitive": True,
                    "variableName": var_name("IORIVER_CLEARED"),
                    "variableExpression": "{{parent.PMUSER_IORIVER_SERVICE_ID}}",
                },
            }
        ],
        "criteriaMustSatisfy": "all",
        "behaviors": [
            set_variable_from_edgescape("IORIVER_ASN", "ASNUM"),
            set_variable_from_edgescape("IORIVER_CITY", "CITY"),
            set_variable_from_edgescape("IORIVER_COUNTRY", "COUNTRY_CODE"),
            set_variable_from_edgescape("IORIVER_REGION", "REGION_CODE"),
            add_header("X-IOR-Security-Sidecar", "true"),
            add_header("X-IOR-Original-Host", "{{builtin.AK_HOST}}"),
            add_header("Host", "{{parent.PMUSER_IORIVER_SECURITY_ORIGIN}}"),
            add_header("X-IOR-Client-IP", "{{builtin.AK_CLIENT_IP}}"),
            add_header(
                "X-IOR-Geodata",
                ",".join(
                    f"{{{{user.{var_name(name)}}}}}"
                    for name in ("IORIVER_COUNTRY", "IORIVER_REGION", "IORIVER_CITY", "IORIVER_ASN")
                ),
            ),
            {
                "name": "origin",
                "options": {
                    "originType": "CUSTOMER",
                    "forwardHostHeader": "ORIGIN_HOSTNAME",
                    "cacheKeyHostname": "ORIGIN_HOSTNAME",
                    "ipVersion": "IPV4",
                    "compress": True,
                    "enableTrueClientIp": True,
                    "trueClientIpHeader": "True-Client-IP",
                    "trueClientIpClientSetting": False,
                    "verificationMode": "CUSTOM",
                    "originSni": True,
                    "httpPort": 80,
                    "httpsPort": 443,
                    "minTlsVersion": "DYNAMIC",
                    "http2Enabled": True,
                    "hostname": "{{parent.PMUSER_IORIVER_SECURITY_ORIGIN}}",
                    "customValidCnValues": ["{{Origin Hostname}}", "{{Forward Host Header}}"],
                    "originCertsToHonor": "STANDARD_CERTIFICATE_AUTHORITIES",
                    "standardCertificateAuthorities": ["akamai-permissive"],
                },
            },
        ],
        "children": [],
    }

    iorriver_security_cleared_rule = {
        "name": "IORiver-Security-Cleared",
        "criteria": [
            {
                "name": "matchVariable",
                "options": {
                    "matchOperator": "IS",
                    "matchWildcard": False,
                    "matchCaseSensitive": True,
                    "variableName": var_name("IORIVER_CLEARED"),
                    "variableExpression": "{{parent.PMUSER_IORIVER_SERVICE_ID}}",
                },
            }
        ],
        "criteriaMustSatisfy": "all",
        "behaviors": [
            add_header("True-Client-IP", f"{{{{user.{var_name('IORIVER_CLIENT_IP')}}}}}"),
        ],
        "children": [],
    }

    return {
        "name": "default",
        "children": [iorriver_variables_rule, iorriver_security_rule, iorriver_security_cleared_rule],
        "behaviors": [],
        "criteria": [],
        "criteriaMustSatisfy": "all",
        "options": {},
        "variables": variables,
    }


def create_session(args):
    """Build an authenticated requests.Session and base URL from .edgerc credentials."""
    edgerc = EdgeRc(str(args.edgerc))
    session = requests.Session()
    session.auth = EdgeGridAuth(
        client_token=edgerc.get("default", "client_token"),
        client_secret=edgerc.get("default", "client_secret"),
        access_token=edgerc.get("default", "access_token"),
    )
    base_url = "https://" + edgerc.get("default", "host")
    return session, base_url


def common_params(args):
    """Query parameters shared by all PAPI calls (contract/group)."""
    return {"contractId": args.contract_id, "groupId": args.group_id}


def get_latest_rule_format(session, base_url, args):
    """Resolve the 'latest' alias to a concrete dated rule format: Akamai's
    create-include endpoint rejects the literal string 'latest'."""
    resp = session.get(
        f"{base_url}/papi/v1/rule-formats",
        params=common_params(args),
        headers={"PAPI-Use-Prefixes": "true"},
    )
    check_response(resp)
    items = resp.json()["ruleFormats"]["items"]
    dated_formats = sorted(item for item in items if item != "latest")
    return dated_formats[-1]


def resolve_product_id(session, base_url, args):
    """Use PRODUCT_ID if this contract is entitled to it, otherwise fall back to the first available product."""
    resp = session.get(
        f"{base_url}/papi/v1/products",
        params=common_params(args),
        headers={"PAPI-Use-Prefixes": "true"},
    )
    check_response(resp)
    items = resp.json()["products"]["items"]
    if not items:
        raise RuntimeError(f"No products available under contract {args.contract_id}")
    if PRODUCT_ID in {item["productId"] for item in items}:
        return PRODUCT_ID
    fallback = items[0]
    print(
        f"Product {PRODUCT_ID} not available on contract {args.contract_id}; using {fallback['productId']} ({fallback['productName']}) instead")
    return fallback["productId"]


def create_include(session, base_url, args):
    """Create a new, empty Include and return its includeId."""
    rule_format = args.rule_format or get_latest_rule_format(session, base_url, args)
    product_id = resolve_product_id(session, base_url, args)
    body = {
        "includeName": INCLUDE_NAME,
        "includeType": "COMMON_SETTINGS",
        "productId": product_id,
        "ruleFormat": rule_format,
    }

    resp = session.post(
        f"{base_url}/papi/v1/includes",
        params=common_params(args),
        headers={"PAPI-Use-Prefixes": "true", "Content-Type": "application/json"},
        json=body,
    )
    check_response(resp)
    include_link = resp.json()["includeLink"]
    include_id = include_link.split("/includes/")[1].split("?")[0]
    print(f"Created include {include_id} ({INCLUDE_NAME})")
    return include_id


def get_rules_etag(session, base_url, args, include_id, version):
    """Fetch the current ETag for an include version's rule tree (needed for If-Match on PUT)."""
    resp = session.get(
        f"{base_url}/papi/v1/includes/{include_id}/versions/{version}/rules",
        params=common_params(args),
        headers={"PAPI-Use-Prefixes": "true"},
    )
    check_response(resp)
    # Fall back to the body's "etag" field: the ETag header is sometimes absent.
    etag = resp.headers.get("ETag") or resp.json().get("etag")
    if not etag:
        raise RuntimeError(f"No ETag found in response for include {include_id} version {version}")
    # If-Match must be a quoted entity-tag; the body's "etag" field lacks the
    # surrounding quotes that the ETag header normally includes.
    if not etag.startswith('"'):
        etag = f'"{etag}"'
    return etag


def put_rules(session, base_url, args, include_id, rule_tree, version):
    """Write the rule tree to an include version."""
    etag = get_rules_etag(session, base_url, args, include_id, version)
    resp = session.put(
        f"{base_url}/papi/v1/includes/{include_id}/versions/{version}/rules",
        params=common_params(args),
        headers={"PAPI-Use-Prefixes": "true", "Content-Type": "application/json", "If-Match": etag},
        json={"rules": rule_tree},
    )
    check_response(resp)
    print(f"Rule tree saved for include {include_id} version {version}")
    return resp.json()


def main():
    args = parse_args()

    if args.dry_run:
        print(json.dumps(build_rule_tree("REPLACE_WITH_INCLUDE_ID"), indent=2))
        return

    session, base_url = create_session(args)

    # version is always 1: this script only bootstraps a fresh Include (Part A).
    version = 1
    include_id = create_include(session, base_url, args)
    rule_tree = build_rule_tree(numeric_id(include_id))
    put_rules(session, base_url, args, include_id, rule_tree, version)


if __name__ == "__main__":
    main()
