"""Main module for Okta API interactions."""

import json
import os
import sys

import requests
from services.enrollment import generate_server_enrollment_token
from services.resource_groups import (
    get_projects_by_resource_group,
    get_resource_groups_by_team,
)
from services.service_token import get_service_token


def execute_api_cycle(
    org_name: str | None = None,
    team_name: str | None = None,
    target_project: str | None = None,
    key_id: str | None = None,
    key_secret: str | None = None,
    output_json: bool = False,
) -> None:
    """Execute the Okta API cycle."""
    # Use provided values or read from environment
    org_name = org_name or os.getenv("OKTA_ORG")
    team_name = team_name or os.getenv("OKTA_TEAM")
    target_project = target_project or os.getenv("OKTA_TARGET_PROJECT")

    if not team_name or not org_name or not target_project:
        raise ValueError(
            "org_name, team_name, and target_project variables must be set"
        )

    key_id = key_id or os.getenv("KEY_ID")
    key_secret = key_secret or os.getenv("KEY_SECRET")

    if not key_id or not key_secret:
        raise ValueError("key_id and key_secret variables must be set")

    try:
        data = get_service_token(org_name, team_name, key_id, key_secret)
        bearer_token = data["bearer_token"]
        # print(f"Obtained bearer token: \n{bearer_token}\n")
        # print(data)
        resource_groups = get_resource_groups_by_team(bearer_token, org_name, team_name)
        for rg in resource_groups:
            # print(rg)
            projects = get_projects_by_resource_group(
                bearer_token, org_name, team_name, rg["id"]
            )
            rg["__projects"] = projects

        # print(json.dumps(resource_groups, indent=2))

        et = generate_server_enrollment_token(
            team_name,
            target_project,
            org_name,
            bearer_token,
            resource_group_id=resource_groups[0]["id"],
            project_id=resource_groups[0]["__projects"][0]["id"],
            description="Generated by script",
        )
        token = et["token"]
        if not token:
            raise ValueError("No token received")
        if output_json:
            print(json.dumps(et, indent=2))
        else:
            print(f"{et['token']}")

        # projects = get_projects_by_team(bearer_token, org_name, team_name)
        # print(projects)
    except requests.exceptions.RequestException as e:
        print(f"Error making API request: {e}", file=sys.stderr)
    except ValueError as e:
        print(f"Configuration error: {e}", file=sys.stderr)


if __name__ == "__main__":
    execute_api_cycle()
