"""LEGAL DISCLAIMER:

This script is provided "as is" as a code sample for demonstration purposes only.
Modigie, Inc. makes no representations or warranties of any kind, express or implied,
about the completeness, accuracy, reliability, suitability, or availability with respect
to this script for any purpose. Any reliance you place on such information is therefore
strictly at your own risk.

In no event will we be liable for any loss or damage including without limitation,
indirect or consequential loss or damage, or any loss or damage whatsoever arising
from loss of data or profits arising out of, or in connection with, the use of this script.

This script is not intended for production use.
"""

import json
import os
from typing import Optional, Tuple

from google.oauth2 import service_account


SUPPORTED_JOB_TYPES: Tuple[str, ...] = (
    "enrichMobile",
    "verifyEmployment",
    "verifyMobile",
    "enrichLinkedIn",
    "verifyPhone",
)

DEFAULT_TENANT_PROJECT_ID: str = "modigie-c-q8irqgvocgg8lt4dwa3e"
DEFAULT_REPO_SHORT_ID: str = "2678a46bd60d84c"


# --8<-- [start:configuration]
class UtilConfig:
    """Centralized configuration for the Quick Quality Test Utility."""

    # Google Cloud Project ID hosting the Modigie tenant Pub/Sub resources.
    # Pre-configured for Cloud Workstations; can be overridden via MODIGIE_TENANT_PROJECT_ID.
    tenantProjectId: str = os.getenv("MODIGIE_TENANT_PROJECT_ID", DEFAULT_TENANT_PROJECT_ID)

    # Short hash (first 15 hex characters) of the Modigie repository ID.
    # Pre-configured for Cloud Workstations; can be overridden via MODIGIE_REPO_SHORT_ID.
    repoShortId: str = os.getenv("MODIGIE_REPO_SHORT_ID", DEFAULT_REPO_SHORT_ID)

    credentialsPath: Optional[str] = None
    credentialsJson: Optional[str] = None

    def __init__(
        self,
        tenantProjectId: Optional[str] = None,
        repoShortId: Optional[str] = None,
        credentialsPath: Optional[str] = None,
        credentialsJson: Optional[str] = None,
    ):
        if tenantProjectId:
            self.tenantProjectId = tenantProjectId
        elif os.getenv("MODIGIE_TENANT_PROJECT_ID"):
            self.tenantProjectId = os.environ["MODIGIE_TENANT_PROJECT_ID"]
        else:
            self.tenantProjectId = DEFAULT_TENANT_PROJECT_ID

        if repoShortId:
            self.repoShortId = repoShortId
        elif os.getenv("MODIGIE_REPO_SHORT_ID"):
            self.repoShortId = os.environ["MODIGIE_REPO_SHORT_ID"]
        else:
            self.repoShortId = DEFAULT_REPO_SHORT_ID

        self.credentialsPath = credentialsPath
        self.credentialsJson = credentialsJson or os.getenv("MODIGIE_CREDENTIALS_JSON")

    def get_credentials(self) -> Optional[service_account.Credentials]:
        """Resolve Google Cloud credentials using file path, in-memory JSON, or fallback."""
        # 1. File path provided
        if self.credentialsPath:
            if not os.path.isfile(self.credentialsPath):
                raise FileNotFoundError(f"Credentials file not found: {self.credentialsPath}")
            return service_account.Credentials.from_service_account_file(self.credentialsPath)

        # 2. In-memory JSON content
        rawJson = (self.credentialsJson or "").strip()
        if rawJson:
            try:
                info = json.loads(rawJson)
            except json.JSONDecodeError as err:
                raise ValueError(f"MODIGIE_CREDENTIALS_JSON contains invalid JSON: {err}") from err
            try:
                return service_account.Credentials.from_service_account_info(info)
            except Exception as err:
                raise ValueError(f"Failed to load credentials from MODIGIE_CREDENTIALS_JSON: {err}") from err

        # 3. Standard GCP fallback
        return None

    def get_topic_id(self, jobType: str) -> str:
        """Compute Pub/Sub request topic ID for a supported job type."""
        if jobType not in SUPPORTED_JOB_TYPES:
            raise ValueError(f"Unsupported job type: '{jobType}'. Supported types: {list(SUPPORTED_JOB_TYPES)}")
        return f"inpubsub-job-request-{jobType.lower()}-{self.repoShortId}"

    def get_topic_path(self, jobType: str) -> str:
        """Fully-qualified Pub/Sub request topic path for a supported job type."""
        return f"projects/{self.tenantProjectId}/topics/{self.get_topic_id(jobType)}"

    def get_subscription_id(self, jobType: str) -> str:
        """Compute Pub/Sub response pull subscription ID for a supported job type."""
        if jobType not in SUPPORTED_JOB_TYPES:
            raise ValueError(f"Unsupported job type: '{jobType}'. Supported types: {list(SUPPORTED_JOB_TYPES)}")
        return f"inpubsub-job-response-{jobType.lower()}-pull-all-externalendpoint-{self.repoShortId}"

    def get_subscription_path(self, jobType: str) -> str:
        """Fully-qualified Pub/Sub response pull subscription path for a supported job type."""
        return f"projects/{self.tenantProjectId}/subscriptions/{self.get_subscription_id(jobType)}"


# --8<-- [end:configuration]
