"""
Diagnostic script to test the personal branch flow step by step.
Run with your env vars set:

    export LOOKER_BASE_URL="https://..."
    export LOOKER_CLIENT_ID="..."
    export LOOKER_CLIENT_SECRET="..."
    export LOOKER_PROJECT="..."
    /Library/Developer/CommandLineTools/usr/bin/python3 test_personal_branch_diagnostic.py
"""

import asyncio
import logging
import os
import sys

# Set up verbose logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s | %(message)s")
logger = logging.getLogger(__name__)

from looker_validator.async_client import AsyncLookerClient
from looker_validator.branch_manager import AsyncBranchManager


async def run_diagnostic():
    base_url = os.environ.get("LOOKER_BASE_URL")
    client_id = os.environ.get("LOOKER_CLIENT_ID")
    client_secret = os.environ.get("LOOKER_CLIENT_SECRET")
    project = os.environ.get("LOOKER_PROJECT")
    test_branch = os.environ.get("LOOKER_TEST_BRANCH", "dev-svc-looker-ad-service-account-zhcw")

    missing = [k for k, v in {"LOOKER_BASE_URL": base_url, "LOOKER_CLIENT_ID": client_id,
               "LOOKER_CLIENT_SECRET": client_secret, "LOOKER_PROJECT": project}.items() if not v]
    if missing:
        print(f"ERROR: Missing env vars: {', '.join(missing)}")
        sys.exit(1)

    print(f"\n{'='*60}")
    print(f"PERSONAL BRANCH DIAGNOSTIC")
    print(f"{'='*60}")
    print(f"  Base URL:     {base_url}")
    print(f"  Project:      {project}")
    print(f"  Test Branch:  {test_branch}")
    print(f"{'='*60}\n")

    async with AsyncLookerClient(
        base_url=base_url,
        client_id=client_id,
        client_secret=client_secret,
    ) as client:
        # Store project on client for cache busting
        client.project = project

        # Step 1: Get initial state
        print("[Step 1] Getting initial project state...")
        try:
            workspace = await client.get_workspace()
            branch_info = await client.get_active_branch(project)
            print(f"  OK - workspace={workspace}, branch={branch_info['name']}")
        except Exception as e:
            print(f"  FAILED - {e}")
            return

        # Step 2: Switch to dev mode
        print("\n[Step 2] Switching to dev workspace...")
        try:
            await client.update_workspace("dev")
            print(f"  OK")
        except Exception as e:
            print(f"  FAILED - {e}")
            return

        # Step 3: Find personal branch
        print("\n[Step 3] Finding personal branch...")
        try:
            branches = await client.get_all_branches(project)
            personal = None
            for b in branches:
                if b.get("personal") and not b.get("readonly"):
                    personal = b["name"]
                    break
            if personal:
                print(f"  OK - personal branch: {personal}")
            else:
                print(f"  FAILED - no personal branch found")
                print(f"  Available branches (first 10):")
                for b in branches[:10]:
                    print(f"    {b['name']} (personal={b.get('personal')}, readonly={b.get('readonly')})")
                return
        except Exception as e:
            print(f"  FAILED - {e}")
            return

        # Step 4: Checkout personal branch
        print(f"\n[Step 4] Checking out personal branch '{personal}'...")
        try:
            await client.checkout_branch(project, personal)
            print(f"  OK")
        except Exception as e:
            print(f"  FAILED - {e}")
            return

        # Step 5: Reset to remote
        print(f"\n[Step 5] Resetting to remote...")
        try:
            await client.reset_to_remote(project)
            print(f"  OK")
        except Exception as e:
            print(f"  FAILED (non-fatal) - {e}")

        # Step 6: Hard reset to target branch ref
        print(f"\n[Step 6] Hard resetting '{personal}' to ref '{test_branch}'...")
        try:
            await client.hard_reset_branch(project, personal, test_branch)
            print(f"  OK")
        except Exception as e:
            print(f"  FAILED - {e}")
            print(f"\n  Trying with 'origin/{test_branch}' as ref instead...")
            try:
                await client.hard_reset_branch(project, personal, f"origin/{test_branch}")
                print(f"  OK with origin/ prefix")
            except Exception as e2:
                print(f"  ALSO FAILED - {e2}")
            return

        # Step 7: Verify
        print(f"\n[Step 7] Verifying current state...")
        try:
            branch_info = await client.get_active_branch(project)
            print(f"  OK - now on branch: {branch_info['name']}")
        except Exception as e:
            print(f"  FAILED - {e}")

        # Cleanup: restore to production
        print(f"\n[Cleanup] Restoring to production workspace...")
        try:
            await client.update_workspace("production")
            print(f"  OK")
        except Exception as e:
            print(f"  FAILED - {e}")

    print(f"\n{'='*60}")
    print(f"DIAGNOSTIC COMPLETE")
    print(f"{'='*60}\n")


if __name__ == "__main__":
    asyncio.run(run_diagnostic())
