export const remotePythonProfitScript = String.raw`

def profit_decimal(value):
    from decimal import Decimal, InvalidOperation
    if value is None or isinstance(value, bool):
        return Decimal("0")
    try:
        return Decimal(str(value))
    except (InvalidOperation, ValueError):
        return Decimal("0")

def profit_decimal_text(value):
    text_value = format(value, "f")
    if "." in text_value:
        text_value = text_value.rstrip("0").rstrip(".")
    return text_value or "0"

def profit_parse_time(value):
    if not isinstance(value, str) or not value:
        return None
    try:
        parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
        return parsed.replace(tzinfo=timezone.utc) if parsed.tzinfo is None else parsed.astimezone(timezone.utc)
    except ValueError:
        return None

def profit_window_start(window, end_at):
    matched = re.fullmatch(r"([1-9][0-9]*)([smhd])", str(window or ""))
    if matched is None:
        raise RuntimeError("profit window must be a duration such as 24h")
    amount = int(matched.group(1))
    unit = matched.group(2)
    seconds = amount * {"s": 1, "m": 60, "h": 3600, "d": 86400}[unit]
    return end_at - timedelta(seconds=seconds)

def profit_period_bounds(window, month, end_at):
    if month is None:
        return profit_window_start(window, end_at), end_at, None, end_at
    matched = re.fullmatch(r"(\d{4})-(0[1-9]|1[0-2])", str(month))
    if matched is None:
        raise RuntimeError("profit month must use YYYY-MM")
    year = int(matched.group(1))
    month_number = int(matched.group(2))
    start_at = datetime(year, month_number, 1, tzinfo=timezone.utc)
    next_at = datetime(year + 1, 1, 1, tzinfo=timezone.utc) if month_number == 12 else datetime(year, month_number + 1, 1, tzinfo=timezone.utc)
    if start_at > end_at:
        raise RuntimeError("profit month must not be in the future")
    return start_at, min(next_at, end_at), str(month), next_at

def profit_group_class(name, config):
    groups = config.get("groups") if isinstance(config.get("groups"), dict) else {}
    if name in (groups.get("profitable") or []):
        return "profit"
    if name in (groups.get("selfUse") or []):
        return "self-use"
    if name in (groups.get("excluded") or []):
        return "excluded"
    return "unclassified"

def profit_account_rate(name):
    matched = re.search(r"(?:^|\s)([0-9]+(?:\.[0-9]+)?)$", str(name or "").strip())
    return profit_decimal(matched.group(1)) if matched is not None else None

def profit_usage_rows(token, group_id, start_at, end_at):
    rows = []
    page = 1
    page_size = 100
    while True:
        query = (
            f"/api/v1/admin/usage?page={page}&page_size={page_size}&group_id={group_id}"
            f"&start_date={start_at.date().isoformat()}&end_date={end_at.date().isoformat()}"
            "&timezone=UTC&sort_by=created_at&sort_order=desc"
        )
        data = ensure_success(curl_api("GET", query, bearer=token), f"list usage for group {group_id}")
        batch = extract_items(data)
        reached_start = False
        for row in batch:
            if not isinstance(row, dict):
                continue
            created_at = profit_parse_time(row.get("created_at"))
            if created_at is not None and created_at < start_at:
                reached_start = True
                continue
            if created_at is not None and created_at <= end_at:
                rows.append(row)
        total = int(data.get("total", len(rows))) if isinstance(data, dict) else len(rows)
        if not batch or len(batch) < page_size or reached_start or page * page_size >= total:
            return rows, page
        page += 1

def profit_usage_stats(token, group_id, account_id, start_at, end_at):
    query = (
        f"/api/v1/admin/usage/stats?group_id={group_id}&account_id={account_id}"
        f"&start_date={start_at.date().isoformat()}&end_date={end_at.date().isoformat()}&timezone=UTC&nocache=1"
    )
    data = ensure_success(curl_api("GET", query, bearer=token), f"get usage stats for group {group_id} account {account_id}")
    return {
        "request_count": int(data.get("total_requests") or 0) if isinstance(data, dict) else 0,
        "input_tokens": int(data.get("total_input_tokens") or 0) if isinstance(data, dict) else 0,
        "output_tokens": int(data.get("total_output_tokens") or 0) if isinstance(data, dict) else 0,
        "actual_cost": profit_decimal(data.get("total_actual_cost") if isinstance(data, dict) else None),
    }

def profit_row_account_id(row):
    for key in ("account_id", "accountId"):
        if row.get(key) is not None:
            return row.get(key)
    account = row.get("account")
    return account.get("id") if isinstance(account, dict) else None

def profit_row_account_name(row):
    for key in ("account_name", "accountName"):
        if isinstance(row.get(key), str) and row.get(key):
            return row.get(key)
    account = row.get("account")
    return account.get("name") if isinstance(account, dict) else None

def profit_add_usage(target, row, cost_field):
    target["requestCount"] += 1
    target["inputTokens"] += int(row.get("input_tokens") or 0)
    target["outputTokens"] += int(row.get("output_tokens") or 0)
    target["apiAmount"] += profit_decimal(row.get(cost_field))

def profit_add_stats(target, stats, cost_field):
    target["requestCount"] += int(stats.get("request_count") or 0)
    target["inputTokens"] += int(stats.get("input_tokens") or 0)
    target["outputTokens"] += int(stats.get("output_tokens") or 0)
    target["apiAmount"] += profit_decimal(stats.get(cost_field))

def profit_empty_account(group, group_class, account_id, account_name):
    return {
        "groupId": group.get("id"),
        "groupName": group.get("name"),
        "class": group_class,
        "accountId": account_id,
        "accountName": account_name,
        "requestCount": 0,
        "inputTokens": 0,
        "outputTokens": 0,
        "apiAmount": profit_decimal(0),
    }

def profit_build_scenario(spec, account_rows, period_costs, start_at, end_at, period_end_at, forecast, unclassified):
    if not isinstance(spec, dict):
        return None
    selectors = [str(item).strip() for item in (spec.get("withoutAccounts") or []) if str(item).strip()]
    selected_rows = [row for row in account_rows if str(row.get("accountId")) in selectors or str(row.get("accountName")) in selectors]
    matched_selectors = {
        selector for selector in selectors
        if any(str(row.get("accountId")) == selector or str(row.get("accountName")) == selector for row in selected_rows)
    }
    unmatched = [selector for selector in selectors if selector not in matched_selectors]
    if unmatched:
        raise RuntimeError("profit scenario account selector not found: " + ", ".join(unmatched))
    sale_rate = profit_decimal(spec.get("saleRateCnyPerApiUsd"))
    if sale_rate < 0:
        raise RuntimeError("profit scenario sale rate must be non-negative")
    scale = profit_decimal(forecast.get("scale")) if isinstance(forecast, dict) else profit_decimal(1)
    period_seconds = profit_decimal(forecast.get("fullPeriodSeconds")) if isinstance(forecast, dict) else profit_decimal((end_at - start_at).total_seconds())
    period_days = period_seconds / profit_decimal(86400)
    if period_days <= 0:
        raise RuntimeError("profit scenario has no observed period")
    selected_names = {str(row.get("accountName")) for row in selected_rows}
    retained_period_costs = [item for item in period_costs if str(item.get("accountName")) not in selected_names]
    retained_period_cost = sum((profit_decimal(item.get("amountCny")) for item in retained_period_costs), profit_decimal(0))
    removed_period_cost = sum((profit_decimal(item.get("amountCny")) for item in period_costs), profit_decimal(0)) - retained_period_cost
    warnings = []
    complete = not unclassified
    if unclassified:
        warnings.append("unclassified traffic remains outside the scenario")
    class_results = {}
    for group_class in ("profit", "self-use"):
        class_rows = [row for row in account_rows if row.get("class") == group_class]
        chosen = [row for row in class_rows if row in selected_rows]
        remaining = [row for row in class_rows if row not in selected_rows]
        missing_remaining = [row for row in remaining if row.get("completeness") != "complete"]
        total_basis = sum((profit_decimal(row.get("apiAmountUsd")) for row in class_rows), profit_decimal(0))
        selected_basis = sum((profit_decimal(row.get("apiAmountUsd")) for row in chosen), profit_decimal(0))
        remaining_basis = sum((profit_decimal(row.get("apiAmountUsd")) for row in remaining), profit_decimal(0))
        remaining_cost = sum((profit_decimal(row.get("upstreamCostCny")) for row in remaining if row.get("upstreamCostCny") is not None), profit_decimal(0))
        weighted_rate = remaining_cost / remaining_basis if remaining_basis > 0 else None
        replacement_cost = selected_basis * weighted_rate if weighted_rate is not None else (profit_decimal(0) if selected_basis == 0 else None)
        if missing_remaining:
            complete = False
            warnings.append(f"{group_class} remaining accounts have missing cost rates")
        if selected_basis > 0 and remaining_basis <= 0:
            complete = False
            warnings.append(f"{group_class} has no remaining traffic basis for redistribution")
        class_results[group_class] = {
            "class": group_class,
            "totalBasis": total_basis,
            "selectedBasis": selected_basis,
            "remainingBasis": remaining_basis,
            "remainingCost": remaining_cost,
            "weightedRate": weighted_rate,
            "replacementCost": replacement_cost,
            "selectedSharePct": selected_basis * profit_decimal(100) / total_basis if total_basis > 0 else profit_decimal(0),
            "remainingLoadIncreasePct": selected_basis * profit_decimal(100) / remaining_basis if remaining_basis > 0 else None,
            "missingRemaining": missing_remaining,
        }
    profit_class = class_results["profit"]
    self_class = class_results["self-use"]
    revenue = profit_class["totalBasis"] * sale_rate * scale
    theoretical_profit_cost = profit_class["remainingCost"] * scale
    theoretical_self_cost = self_class["remainingCost"] * scale
    theoretical_without_self = revenue - theoretical_profit_cost - retained_period_cost
    theoretical_with_self = theoretical_without_self - theoretical_self_cost
    redistributed_profit_cost = theoretical_profit_cost + (profit_class["replacementCost"] * scale if profit_class["replacementCost"] is not None else profit_decimal(0))
    redistributed_self_cost = theoretical_self_cost + (self_class["replacementCost"] * scale if self_class["replacementCost"] is not None else profit_decimal(0))
    redistributed_without_self = revenue - redistributed_profit_cost - retained_period_cost
    redistributed_with_self = redistributed_without_self - redistributed_self_cost
    selected_accounts = {}
    for row in selected_rows:
        key = (str(row.get("accountId")), str(row.get("accountName")))
        if key not in selected_accounts:
            selected_accounts[key] = {"accountId": row.get("accountId"), "accountName": row.get("accountName"), "classes": []}
        if row.get("class") not in selected_accounts[key]["classes"]:
            selected_accounts[key]["classes"].append(row.get("class"))
    redistribution = []
    for item in (profit_class, self_class):
        redistribution.append({
            "class": item["class"],
            "selectedApiUsd": profit_decimal_text(item["selectedBasis"] * scale),
            "selectedSharePct": profit_decimal_text(item["selectedSharePct"]),
            "remainingWeightedCostRateCnyPerApiUsd": profit_decimal_text(item["weightedRate"]) if item["weightedRate"] is not None else None,
            "replacementCostCny": profit_decimal_text(item["replacementCost"] * scale) if item["replacementCost"] is not None else None,
            "remainingLoadIncreasePct": profit_decimal_text(item["remainingLoadIncreasePct"]) if item["remainingLoadIncreasePct"] is not None else None,
            "missingRemainingCostAccounts": [{"accountId": row.get("accountId"), "accountName": row.get("accountName")} for row in item["missingRemaining"]],
        })
    status = "complete" if complete else "partial"
    return {
        "status": status,
        "method": "remaining-account-weighted-cost-redistribution",
        "scale": profit_decimal_text(scale),
        "saleRateCnyPerApiUsd": profit_decimal_text(sale_rate),
        "selectedAccounts": list(selected_accounts.values()),
        "removedPeriodCostCny": profit_decimal_text(removed_period_cost),
        "retainedPeriodCostCny": profit_decimal_text(retained_period_cost),
        "theoretical": {
            "withoutSelfUseProfitCny": profit_decimal_text(theoretical_without_self) if complete else None,
            "withSelfUseProfitCny": profit_decimal_text(theoretical_with_self) if complete else None,
        },
        "redistributed": {
            "revenueCny": profit_decimal_text(revenue),
            "costsCny": {
                "profitPool": profit_decimal_text(redistributed_profit_cost) if complete else None,
                "selfUse": profit_decimal_text(redistributed_self_cost) if complete else None,
                "period": profit_decimal_text(retained_period_cost),
            },
            "profitCny": {
                "withoutSelfUse": profit_decimal_text(redistributed_without_self) if complete else None,
                "withSelfUse": profit_decimal_text(redistributed_with_self) if complete else None,
            },
        },
        "dailyAverage": {
            "days": profit_decimal_text(period_days),
            "revenueCny": profit_decimal_text(revenue / period_days),
            "costsCny": {
                "profitPool": profit_decimal_text(redistributed_profit_cost / period_days) if complete else None,
                "selfUse": profit_decimal_text(redistributed_self_cost / period_days) if complete else None,
                "period": profit_decimal_text(retained_period_cost / period_days),
            },
            "profitCny": {
                "withoutSelfUse": profit_decimal_text(redistributed_without_self / period_days) if complete else None,
                "withSelfUse": profit_decimal_text(redistributed_with_self / period_days) if complete else None,
            },
        },
        "redistribution": redistribution,
        "warnings": warnings,
    }

def run_profit_report():
    payload = json.loads(base64.b64decode(PAYLOAD_B64).decode("utf-8")) if PAYLOAD_B64 else {}
    config = payload.get("config") if isinstance(payload.get("config"), dict) else {}
    window = payload.get("since")
    requested_month = payload.get("month")
    cost_field = config.get("usageCostField")
    sale_rate = profit_decimal(config.get("saleRateCnyPerApiUsd"))
    end_at = datetime.now(timezone.utc)
    start_at, end_at, month, period_end_at = profit_period_bounds(window, requested_month, end_at)
    period_costs = [item for item in (config.get("periodCosts") or []) if isinstance(item, dict) and item.get("period") == month]
    period_cost = sum((profit_decimal(item.get("amountCny")) for item in period_costs), profit_decimal(0))
    _, token, _ = login()
    groups = [item for item in list_groups(token) if isinstance(item, dict)]
    account_rows = []
    group_rows = []
    total_pages = 0
    configured_names = set()
    configured_groups = config.get("groups") if isinstance(config.get("groups"), dict) else {}
    for names in configured_groups.values():
        if isinstance(names, list):
            configured_names.update(str(name) for name in names)
    runtime_names = {str(group.get("name")) for group in groups}
    for group in sorted(groups, key=lambda item: int(item.get("id") or 0)):
        group_id = group.get("id")
        group_name = str(group.get("name") or "")
        group_class = profit_group_class(group_name, config)
        members = list_accounts_for_group(token, group_id)
        accounts_by_id = {str(item.get("id")): item for item in members if isinstance(item, dict) and item.get("id") is not None}
        aggregates = {}
        if month is not None:
            for account in members:
                if not isinstance(account, dict) or account.get("id") is None:
                    continue
                account_id = account.get("id")
                account_name = account.get("name") or f"account-{account_id}"
                stats = profit_usage_stats(token, group_id, account_id, start_at, end_at)
                total_pages += 1
                if int(stats.get("request_count") or 0) <= 0:
                    continue
                aggregates[str(account_id)] = profit_empty_account(group, group_class, account_id, account_name)
                profit_add_stats(aggregates[str(account_id)], stats, cost_field)
        else:
            usage, pages = profit_usage_rows(token, group_id, start_at, end_at)
            total_pages += pages
            for row in usage:
                account_id = profit_row_account_id(row)
                account = accounts_by_id.get(str(account_id))
                account_name = profit_row_account_name(row) or (account.get("name") if isinstance(account, dict) else None) or f"account-{account_id}"
                key = str(account_id) if account_id is not None else "name:" + str(account_name)
                if key not in aggregates:
                    aggregates[key] = profit_empty_account(group, group_class, account_id, account_name)
                profit_add_usage(aggregates[key], row, cost_field)
        group_amount = profit_decimal(0)
        group_tokens = 0
        group_requests = 0
        for aggregate in aggregates.values():
            rate = profit_account_rate(aggregate["accountName"])
            amount = aggregate.pop("apiAmount")
            revenue = amount * sale_rate if group_class == "profit" else profit_decimal(0)
            upstream_cost = amount * rate if rate is not None and group_class in ("profit", "self-use") else profit_decimal(0)
            aggregate["tokenCount"] = aggregate.pop("inputTokens") + aggregate.pop("outputTokens")
            aggregate["apiAmountUsd"] = profit_decimal_text(amount)
            aggregate["costRateCnyPerApiUsd"] = profit_decimal_text(rate) if rate is not None else None
            aggregate["revenueCny"] = profit_decimal_text(revenue)
            aggregate["upstreamCostCny"] = profit_decimal_text(upstream_cost) if rate is not None or group_class not in ("profit", "self-use") else None
            aggregate["profitContributionCny"] = profit_decimal_text(revenue - upstream_cost) if rate is not None or group_class not in ("profit", "self-use") else None
            aggregate["completeness"] = "complete" if rate is not None or group_class not in ("profit", "self-use") else "partial"
            account_rows.append(aggregate)
            group_amount += amount
            group_tokens += aggregate["tokenCount"]
            group_requests += aggregate["requestCount"]
        group_rows.append({
            "groupId": group_id,
            "groupName": group_name,
            "class": group_class,
            "requestCount": group_requests,
            "tokenCount": group_tokens,
            "apiAmountUsd": profit_decimal_text(group_amount),
        })
    profit_accounts = [row for row in account_rows if row["class"] == "profit"]
    self_accounts = [row for row in account_rows if row["class"] == "self-use"]
    missing_profit = [row for row in profit_accounts if row["completeness"] != "complete"]
    missing_self = [row for row in self_accounts if row["completeness"] != "complete"]
    unclassified = [row for row in account_rows if row["class"] == "unclassified" and row["requestCount"] > 0]
    revenue = sum((profit_decimal(row["revenueCny"]) for row in profit_accounts), profit_decimal(0))
    profit_cost = sum((profit_decimal(row["upstreamCostCny"]) for row in profit_accounts if row["upstreamCostCny"] is not None), profit_decimal(0))
    self_cost = sum((profit_decimal(row["upstreamCostCny"]) for row in self_accounts if row["upstreamCostCny"] is not None), profit_decimal(0))
    unknown_profit_api_usd = sum((profit_decimal(row["apiAmountUsd"]) for row in missing_profit), profit_decimal(0))
    unknown_self_api_usd = sum((profit_decimal(row["apiAmountUsd"]) for row in missing_self), profit_decimal(0))
    operating_profit_without_self = revenue - profit_cost
    operating_profit_with_self = operating_profit_without_self - self_cost
    profit_before_unknown_without_self = operating_profit_without_self - period_cost
    profit_before_unknown_with_self = operating_profit_with_self - period_cost
    without_complete = not missing_profit and not unclassified
    with_complete = without_complete and not missing_self
    forecast = None
    if payload.get("forecast") is True:
        if month is None:
            raise RuntimeError("profit forecast requires a calendar month")
        observed_seconds = profit_decimal((end_at - start_at).total_seconds())
        full_period_seconds = profit_decimal((period_end_at - start_at).total_seconds())
        if observed_seconds <= 0:
            raise RuntimeError("profit forecast has no observed period")
        scale = full_period_seconds / observed_seconds
        forecast_revenue = revenue * scale
        forecast_profit_cost = profit_cost * scale
        forecast_self_cost = self_cost * scale
        forecast_without_self = forecast_revenue - forecast_profit_cost - period_cost
        forecast_with_self = forecast_without_self - forecast_self_cost
        forecast = {
            "method": "month-to-date-linear-run-rate",
            "scale": profit_decimal_text(scale),
            "observedSeconds": profit_decimal_text(observed_seconds),
            "fullPeriodSeconds": profit_decimal_text(full_period_seconds),
            "revenueCny": profit_decimal_text(forecast_revenue),
            "costsCny": {
                "profitPool": profit_decimal_text(forecast_profit_cost),
                "selfUse": profit_decimal_text(forecast_self_cost),
                "period": profit_decimal_text(period_cost),
            },
            "profitCny": {
                "withoutSelfUse": profit_decimal_text(forecast_without_self) if without_complete else None,
                "withSelfUse": profit_decimal_text(forecast_with_self) if with_complete else None,
            },
            "withoutSelfUse": {"status": "complete" if without_complete else "partial"},
            "withSelfUse": {"status": "complete" if with_complete else "partial"},
        }
    account_rows.sort(key=lambda row: (row["class"], row["groupName"], str(row["accountId"]), str(row["accountName"])))
    scenario = profit_build_scenario(payload.get("scenario"), account_rows, period_costs, start_at, end_at, period_end_at, forecast, unclassified)
    return {
        "ok": True,
        "mode": "profit",
        "status": "complete" if with_complete else "partial",
        "window": {"since": window if month is None else None, "month": month, "startAt": start_at.isoformat(), "endAt": end_at.isoformat(), "timezone": "UTC"},
        "source": {"kind": "sub2api-native-admin-usage", "endpoint": "/api/v1/admin/usage/stats" if month is not None else "/api/v1/admin/usage", "usageCostField": cost_field, "queriesRead": total_pages},
        "policy": config,
        "groups": group_rows,
        "accounts": account_rows,
        "periodCosts": [{"id": item.get("id"), "period": item.get("period"), "accountName": item.get("accountName"), "amountCny": profit_decimal_text(profit_decimal(item.get("amountCny"))), "description": item.get("description")} for item in period_costs],
        "scenario": scenario,
        "summary": {
            "revenueCny": profit_decimal_text(revenue),
            "confirmedCostsCny": {
                "profitPool": profit_decimal_text(profit_cost),
                "selfUse": profit_decimal_text(self_cost),
                "period": profit_decimal_text(period_cost),
                "total": profit_decimal_text(profit_cost + self_cost + period_cost),
            },
            "operatingProfitBeforeUnknownCostsCny": {
                "withoutSelfUse": profit_decimal_text(operating_profit_without_self),
                "withSelfUse": profit_decimal_text(operating_profit_with_self),
            },
            "profitBeforeUnknownCostsCny": {
                "withoutSelfUse": profit_decimal_text(profit_before_unknown_without_self),
                "withSelfUse": profit_decimal_text(profit_before_unknown_with_self),
            },
            "unknownCostBasisApiUsd": {
                "profitPool": profit_decimal_text(unknown_profit_api_usd),
                "selfUse": profit_decimal_text(unknown_self_api_usd),
                "total": profit_decimal_text(unknown_profit_api_usd + unknown_self_api_usd),
            },
            "profitFormula": {
                "withoutSelfUse": "revenueCny - confirmedCostsCny.profitPool - confirmedCostsCny.period - sum(missing profit account apiAmountUsd * unknown costRateCnyPerApiUsd)",
                "withSelfUse": "revenueCny - confirmedCostsCny.profitPool - confirmedCostsCny.selfUse - confirmedCostsCny.period - sum(all missing account apiAmountUsd * unknown costRateCnyPerApiUsd)",
            },
            "withoutSelfUse": {"status": "complete" if without_complete else "partial", "profitCny": profit_decimal_text(profit_before_unknown_without_self) if without_complete else None},
            "withSelfUse": {"status": "complete" if with_complete else "partial", "profitCny": profit_decimal_text(profit_before_unknown_with_self) if with_complete else None},
            "forecast": forecast,
        },
        "completeness": {
            "missingCostAccounts": [{"class": row["class"], "groupName": row["groupName"], "accountId": row["accountId"], "accountName": row["accountName"], "apiAmountUsd": row["apiAmountUsd"]} for row in missing_profit + missing_self],
            "unclassifiedTraffic": [{"groupName": row["groupName"], "accountId": row["accountId"], "accountName": row["accountName"], "requestCount": row["requestCount"]} for row in unclassified],
            "configuredGroupsMissingAtRuntime": sorted(configured_names - runtime_names),
        },
    }
`;
