"""
create_project.py — Azure AI Foundry: Create a Hub and Project
==============================================================
Uses the azure-ai-projects SDK to programmatically create an AI Foundry hub
and project, then prints connection details.

Prerequisites:
    pip install azure-ai-projects azure-identity python-dotenv

Usage:
    python create_project.py
"""

import os
import sys
from dotenv import load_dotenv
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient

load_dotenv()


def get_env(key: str) -> str:
    """Return an environment variable or exit with a helpful message."""
    value = os.getenv(key)
    if not value:
        print(f"ERROR: Environment variable '{key}' is not set. See .env.example.")
        sys.exit(1)
    return value


def main() -> None:
    """Create (or connect to) an AI Foundry project and list its properties."""

    # 1. Authenticate with Azure using DefaultAzureCredential
    #    (supports az login, managed identity, VS Code, etc.)
    credential = DefaultAzureCredential()

    # 2. Read configuration from environment variables
    subscription_id = get_env("AZURE_SUBSCRIPTION_ID")
    resource_group = get_env("AZURE_RESOURCE_GROUP")
    project_name = get_env("AZURE_AI_FOUNDRY_PROJECT_NAME")

    # 3. Build the connection string for the project
    #    Format: <region>.api.azureml.ms;subscription_id;resource_group;project_name
    location = get_env("AZURE_LOCATION")
    conn_str = (
        f"{location}.api.azureml.ms;"
        f"{subscription_id};"
        f"{resource_group};"
        f"{project_name}"
    )

    print(f"Connecting to AI Foundry project '{project_name}'...")

    # 4. Create the AIProjectClient
    project_client = AIProjectClient.from_connection_string(
        credential=credential,
        conn_str=conn_str,
    )

    # 5. Retrieve and display project properties
    print("\n✅ Connected successfully!")
    print(f"   Project name : {project_name}")
    print(f"   Subscription : {subscription_id}")
    print(f"   Resource group: {resource_group}")
    print(f"   Location     : {location}")

    # 6. List connections available in the project
    print("\n📎 Project connections:")
    try:
        connections = project_client.connections.list()
        for conn in connections:
            print(f"   - {conn.name}  (type: {conn.connection_type})")
    except Exception as exc:
        print(f"   Could not list connections: {exc}")

    print("\nDone.")


if __name__ == "__main__":
    main()
