import os
import uuid
from typing import Dict, List, Any, Optional

def setup_lakefs(
    repository: str, 
    service_account: Optional[str] = None,
    storage_namespace: Optional[str] = None
) -> Dict[str, str]:
    """
    Automates the creation of a scoped LakeFS environment.
    Creates a repo, service user, and generates Access Keys.
    
    Returns:
        Dict containing Access Key, Secret Key, and Repository ID.
    """
    try:
        import lakefs
        from lakefs_sdk import AuthApi, ApiClient, Configuration, Policy, Statement, UserCreation, RepositoryCreation
    except ImportError:
        raise ImportError("lakefs and lakefs-sdk are required for environment setup. Run 'pip install lakefs lakefs-sdk'")

    # Use existing credentials to set up the scoped env
    # (Assuming admin credentials are in env or lakectl config)
    client = ApiClient() # uses default config
    auth = AuthApi(client)
    
    user_id = service_account or f"svc-briefcase-{uuid.uuid4().hex[:4]}"
    repo_id = repository
    
    # 1. Create Repository
    if not storage_namespace:
        # Fallback to standard cloud bucket if not provided
        storage_namespace = f"s3://briefcase-ai-lakefs-cloud/repos/{repo_id}"
        
    try:
        from lakefs_sdk import RepositoriesApi
        repos_api = RepositoriesApi(client)
        repos_api.create_repository(RepositoryCreation(
            name=repo_id, 
            storage_namespace=storage_namespace
        ))
    except Exception as e:
        if "already exists" not in str(e): print(f"Warning: Repo creation failed: {e}")

    # 2. Create User
    try:
        auth.create_user(UserCreation(id=user_id))
    except Exception:
        pass # assume exists

    # 3. Create and Attach Policy
    policy_id = f"policy-{repo_id}-scoped"
    statement = [
        Statement(
            effect="allow",
            action=["fs:ReadObject", "fs:WriteObject", "fs:ListObjects", "fs:CreateBranch", "fs:Commit"],
            resource=f"arn:lakefs:fs:::{repo_id}/*"
        ),
        Statement(
            effect="allow",
            action=["fs:CreateBranch", "fs:ListBranches"],
            resource=f"arn:lakefs:fs:::{repo_id}"
        )
    ]
    
    try:
        auth.create_policy(Policy(id=policy_id, statement=statement))
    except Exception:
        pass # assume exists
        
    auth.attach_policy_to_user(user_id, policy_id)

    # 4. Generate Credentials
    creds = auth.create_credentials(user_id)
    
    return {
        "LAKEFS_ACCESS_KEY_ID": creds.access_key_id,
        "LAKEFS_SECRET_ACCESS_KEY": creds.secret_access_key,
        "LAKEFS_REPOSITORY": repo_id
    }
