#!/usr/bin/env python3
"""
Entrypoint script that loads secrets from Infisical and starts Odoo.
"""
import os
import subprocess
import sys

from infisical_sdk import InfisicalSDKClient

# Load Infisical config from environment
INFISICAL_API_URL = os.environ["INFISICAL_API_URL"]
INFISICAL_CLIENT_ID = os.environ["INFISICAL_CLIENT_ID"]
INFISICAL_CLIENT_SECRET = os.environ["INFISICAL_CLIENT_SECRET"]
INFISICAL_PROJECT_ID = os.environ["INFISICAL_PROJECT_ID"]
INFISICAL_ENV = os.environ.get("INFISICAL_ENV", "prod")

# Initialize Infisical client
client = InfisicalSDKClient(host=INFISICAL_API_URL)
client.auth.universal_auth.login(
    client_id=INFISICAL_CLIENT_ID,
    client_secret=INFISICAL_CLIENT_SECRET,
)

# Fetch secrets from /odoo and /shared paths
for secret_path in ["/odoo", "/shared"]:
    try:
        secrets_response = client.secrets.list_secrets(
            environment_slug=INFISICAL_ENV,
            secret_path=secret_path,
            project_id=INFISICAL_PROJECT_ID,
            expand_secret_references=True,
            view_secret_value=True,
        )
        for secret in secrets_response.secrets:
            os.environ[secret.secretKey] = secret.secretValue
            print(f"Loaded secret from {secret_path}: {secret.secretKey}")
    except Exception as e:
        print(f"Warning: Could not load secrets from {secret_path}: {e}")

# Start Odoo with DB config from environment
odoo_cmd = [
    "odoo",
    f"--db_host={os.environ['ODOO_DB_HOST']}",
    f"--db_port={os.environ['ODOO_DB_PORT']}",
    f"--db_user={os.environ['ODOO_DB_USER']}",
    f"--db_password={os.environ['ODOO_DB_PASSWORD']}",
    f"--database={os.environ['ODOO_DB_NAME']}",
]

print(f"Starting Odoo: {' '.join(odoo_cmd[:5])} --db_password=***")
sys.exit(subprocess.call(odoo_cmd))
