"""
Fabric notebook utilities for dlt pipelines.

Handles:
- Cloning repos to /tmp
- Mounting lakehouses dynamically
- Getting destination paths
"""

import os
import shutil
import subprocess
from typing import Dict, Any, Optional

# Default repos to clone
DEFAULT_REPOS = [
    {"name": "vd-dlt-client-side-config", "url": "https://github.com/accelerate-data/vd-dlt-client-side-config.git"},
    {"name": "vd-dlt-connectors", "url": "https://github.com/accelerate-data/vd-dlt-connectors.git"}
]


def clone_repos(
    pat: str,
    base_path: str = "/tmp/vd-dlt",
    repos: list = None
) -> str:
    """
    Clone repos fresh to temp directory.

    Args:
        pat: GitHub personal access token
        base_path: Base path for cloning (default: /tmp/vd-dlt)
        repos: List of repo dicts with 'name' and 'url' keys (default: DEFAULT_REPOS)

    Returns:
        base_path where repos were cloned
    """
    if repos is None:
        repos = DEFAULT_REPOS

    # Clean and create base path
    if os.path.exists(base_path):
        shutil.rmtree(base_path)
    os.makedirs(base_path)

    print(f"Cloning repos to {base_path}...")
    for repo in repos:
        auth_url = repo['url'].replace("https://", f"https://{pat}@")
        repo_path = f"{base_path}/{repo['name']}"

        result = subprocess.run(
            ["git", "clone", "--depth", "1", auth_url, repo_path],
            capture_output=True,
            text=True,
            timeout=120
        )

        if result.returncode == 0:
            print(f"  Cloned: {repo['name']}")
        else:
            error = result.stderr.replace(pat, "***") if result.stderr else "Unknown"
            raise Exception(f"Clone failed for {repo['name']}: {error}")

    print("Done!")
    return base_path


def mount_lakehouse(
    workspace_id: str,
    lakehouse_id: str,
    mount_point: str = "/lakehouse_target"
) -> str:
    """
    Mount a Fabric lakehouse dynamically.

    Args:
        workspace_id: Fabric workspace ID
        lakehouse_id: Lakehouse ID
        mount_point: Mount point name (default: /lakehouse_target)

    Returns:
        Local path to Tables folder (destination_path)
    """
    # notebookutils is pre-imported in Fabric notebooks
    import notebookutils

    onelake_path = f"abfss://{workspace_id}@onelake.dfs.fabric.microsoft.com/{lakehouse_id}"

    print(f"Mounting lakehouse...")
    print(f"  OneLake path: {onelake_path}")
    print(f"  Mount point: {mount_point}")

    # Unmount if already mounted
    try:
        notebookutils.fs.unmount(mount_point)
        print("  Unmounted existing mount")
    except:
        pass

    # Mount the lakehouse
    notebookutils.fs.mount(onelake_path, mount_point)

    # Get the actual local path
    local_mount_path = notebookutils.fs.getMountPath(mount_point)
    destination_path = f"{local_mount_path}/Tables"

    print(f"  Local mount path: {local_mount_path}")
    print(f"  Destination path: {destination_path}")

    # Verify the path exists
    if os.path.exists(destination_path):
        print(f"  Path exists: YES")
    else:
        print(f"  Path exists: NO - creating...")
        os.makedirs(destination_path, exist_ok=True)

    return destination_path


def setup_fabric_environment(
    vault_url: str,
    github_pat_secret: str = "my-github-pat-token",
    source_name: str = None,
    base_path: str = "/tmp/vd-dlt"
) -> Dict[str, Any]:
    """
    Complete setup for Fabric notebook environment.

    Clones repos and mounts lakehouse based on source config.

    Args:
        vault_url: Azure Key Vault URL
        github_pat_secret: Secret name for GitHub PAT
        source_name: Source name to load config for
        base_path: Base path for cloning

    Returns:
        Dict with:
            - base_path: Path where repos are cloned
            - destination_path: Path to write delta tables
            - source_config: Loaded source configuration
    """
    import notebookutils
    import yaml

    # Get PAT from Key Vault
    pat = notebookutils.credentials.getSecret(vault_url, github_pat_secret)

    # Clone repos
    clone_repos(pat, base_path)

    # Load source config
    source_config_path = f"{base_path}/vd-dlt-client-side-config/sources/{source_name}.yml"
    with open(source_config_path, 'r') as f:
        source_config = yaml.safe_load(f)

    # Get target lakehouse info
    target = source_config.get('target', {})
    lakehouse_name = target.get('lakehouse')
    lakehouse_id = target.get('lakehouse_id')
    workspace_id = target.get('workspace_id')

    print(f"Target lakehouse: {lakehouse_name}")
    print(f"  Lakehouse ID: {lakehouse_id}")
    print(f"  Workspace ID: {workspace_id}")

    if not all([lakehouse_id, workspace_id]):
        raise ValueError(f"Missing lakehouse_id or workspace_id in source config for {source_name}")

    # Mount lakehouse
    destination_path = mount_lakehouse(workspace_id, lakehouse_id)

    return {
        "base_path": base_path,
        "destination_path": destination_path,
        "source_config": source_config
    }
