"""
MCP prompt for the MyDrive → Shared Drive migration workflow.

Registers a prompt that client LLMs can request to receive step-by-step
instructions for performing a complete, audited migration.
"""


def register(mcp):

    @mcp.prompt()
    def drive_migration(
        user_email: str = "",
        folder_id: str = "",
        shared_drive_id: str = "",
        sheet_id: str = "",
        domain: str = "",
    ) -> str:
        """
        Returns a step-by-step guide for migrating a MyDrive folder to a
        Shared Drive using the GAMCP migration tools.

        Provide any known parameters up-front; leave blank if unknown and
        the guide will tell you what to ask the user for.
        """
        # Build contextual header
        known = []
        missing = []
        for label, value in [
            ("User email", user_email),
            ("Source folder ID", folder_id),
            ("Destination Shared Drive ID", shared_drive_id),
            ("Audit Google Sheet ID", sheet_id),
            ("Organisation domain", domain),
        ]:
            if value:
                known.append(f"- **{label}**: `{value}`")
            else:
                missing.append(f"- {label}")

        header = "# MyDrive → Shared Drive Migration Workflow\n\n"
        if known:
            header += "## Known Parameters\n" + "\n".join(known) + "\n\n"
        if missing:
            header += (
                "## Parameters Still Needed\n"
                "Ask the user for these before proceeding:\n"
                + "\n".join(missing)
                + "\n\n"
            )

        return header + _MIGRATION_GUIDE


_MIGRATION_GUIDE = """\
## Overview

This workflow performs a **complete, audited migration** of a Google Drive
folder from a user's MyDrive to a Shared Drive.  Every step must be
executed in order.  **Do NOT skip the audit steps** — they are required
to identify ownership issues, external sharing, public files, and broken
shortcuts *before* the move happens.

---

## Pre-Migration Setup

### Step 1 — Suppress todrive emails
Call **`configure_todrive_noemail`** (no arguments).

This sets `todrive_noemail true` so impersonated users do not receive
notification emails every time GAM writes output to Google Sheets.

> Run this once per session before starting any audit steps.

### Google Sheet Preparation
If the user has not provided a `sheet_id`, instruct them to:
1. Create a new Google Sheet named **"Migration Audit"**.
2. Create the following tabs (sheets):
   `file_audit`, `all_permissions`, `file_count`, `own`, `not_owner`,
   `external_owner`, `public_files`, `shortcuts`, `shared_drive_members`,
   `migration_log`, `post_migration_permissions`
3. Share the Sheet ID with you.

---

## Phase 1 — Pre-Migration Audit (Steps 2–10)

All steps in this phase are **read-only**.  They write audit data to the
Google Sheet without modifying any files or permissions.

### Step 2 — Master file inventory
Call **`audit_file_inventory`** with `user_email`, `folder_id`, `sheet_id`.

This is your master inventory.  `filepath` resolves the full path from
root to each item.  `excludetrashed` ensures you are not auditing
deleted content.

**Fields returned:** id, name, mimeType, owners, parents, size,
modifiedTime, createdTime, trashed.

### Step 3 — File count & storage summary
Call **`audit_file_counts`** with `user_email`, `folder_id`, `sheet_id`.

Gives a quick summary of content types and total storage consumed,
broken down per MIME type.  Useful for capacity planning on the Shared
Drive.

### Step 4 — Files owned by the user
Call **`audit_owned_files`** with `user_email`, `folder_id`, `sheet_id`.

Only files the user owns can be *moved* to a Shared Drive.  This
isolates those items.

### Step 5 — Files NOT owned by the user
Call **`audit_not_owned_files`** with `user_email`, `folder_id`, `sheet_id`.

⚠️ **Tell the user** which folders/files are not owned by them.  These
items **cannot** be migrated to the Shared Drive via a standard move.

### Step 6 — Full permissions (ACL) audit
Call **`audit_all_permissions`** with `user_email`, `folder_id`, `sheet_id`.

This is your full Access Control List audit.  Each permission entry gets
its own row (`oneitemperrow`), making it easy to filter and process.

**This sheet is used by Steps 12–14** to reapply permissions after
migration — do not skip it.

### Step 7 — External user permissions
Call **`audit_external_permissions`** with `user_email`, `folder_id`,
`sheet_id`, and `domain` (e.g. `company.com`).

Flags files shared with users outside your organisation.  These may
require cleanup before migrating to a Shared Drive with different
sharing policies.

### Step 8 — Public files ("anyone with the link")
Call **`audit_public_files`** with `user_email`, `folder_id`, `sheet_id`.

These are the **highest-risk** files from a security standpoint.  Shared
Drives can restrict public sharing at the drive level, so you need to
know what you are inheriting.

### Step 9 — Shortcuts
Call **`audit_shortcuts`** with `user_email`, `folder_id`, `sheet_id`.

Shortcuts pointing to files outside the migration scope will **break**
after the move.  `shortcutDetails` returns the `targetId` and
`targetMimeType` so you can determine whether the target will also be
in the Shared Drive post-migration.

### Step 10 — Shared Drive membership
Call **`audit_shared_drive_members`** with `user_email`, `sheet_id`.

Confirms the destination Shared Drive exists and who has what level of
access.  The migrating user **must be a Manager** on the Shared Drive to
move files into it.

---

## Review Checkpoint

**Before proceeding to Step 11, present the user with a summary of
findings from the audits:**

1. Total files and storage (Step 3).
2. Files they do NOT own that cannot be migrated (Step 5).
3. External sharing that may need cleanup (Step 7).
4. Public files that pose a security risk (Step 8).
5. Shortcuts that may break (Step 9).
6. Confirmation that they are a Manager on the destination Shared Drive
   (Step 10).

**Only proceed when the user explicitly confirms.**

---

## Phase 2 — Migration Execution (Step 11)

### Step 11 — Move to Shared Drive
Call **`execute_migration_move`** with `user_email`, `folder_id`,
`shared_drive_id`, `sheet_id`, and `confirmed=True`.

This recursively copies the entire folder tree to the Shared Drive:
- `copyfilepermissions true` — file-level ACLs are copied.
- `duplicatefiles overwriteolder` / `duplicatefolders merge` — handles
  re-runs gracefully.
- `excludetrashed` — skips trashed items.

A CSV log of what was copied is written to the `migration_log` tab.

---

## Phase 3 — Permission Reapplication (Steps 12–14)

These steps read from the **`all_permissions`** audit sheet (Step 6) and
re-create the ACLs on the copied files in the Shared Drive.

> **INFO:** Ownership cannot be transferred via ACL on a Shared Drive.
> In Shared Drives, the drive itself is the owner — individual file
> ownership as it existed in MyDrive does not apply.  GAM will
> automatically skip any `owner` role rows from your audit sheet.
> This is correct and expected behaviour.

### Step 12 — Reapply user & group permissions
Call **`reapply_user_group_permissions`** with `user_email`, `sheet_id`,
and `confirmed=True`.

Processes only rows where `permission.type` is `user` or `group`.

### Step 13 — Reapply domain permissions
Call **`reapply_domain_permissions`** with `user_email`, `sheet_id`,
and `confirmed=True`.

Processes only rows where `permission.type` is `domain`.  Preserves the
`allowFileDiscovery` setting.

### Step 14 — Reapply anyone permissions (if applicable)
Call **`reapply_anyone_permissions`** with `user_email`, `sheet_id`,
and `confirmed=True`.

Only needed if the audit (Step 8) found public files.  Consider whether
public access is appropriate on the destination Shared Drive before
confirming.

---

## Phase 4 — Post-Migration Verification (Step 15)

### Step 15 — Post-migration permissions audit
Call **`audit_post_migration_permissions`** with `user_email`,
`shared_drive_id`, `sheet_id`.

Run one final audit against the Shared Drive to confirm the permissions
match what was recorded pre-migration.  You can then diff the
`all_permissions` tab against `post_migration_permissions` to verify
correctness.

---

## Understanding todrive Arguments

Every audit command uses these arguments to write output directly to the
Google Sheet:

| Argument | Purpose |
|----------|---------|
| `todrive` | Upload output to Google Drive instead of printing to CSV locally |
| `tdfileid <SHEET_ID>` | Specifies the exact Google Sheet to write to |
| `tdsheet <sheet_name>` | Specifies which tab/sheet within that file |
| `tdupdatesheet` | Overwrites the sheet's existing data (not append) |
| `tdretaintitle` | Keeps the sheet tab name unchanged after writing |
"""
