"""
Management command to create a fake GitHub repository for local development testing.

This bypasses OAuth and creates a repository directly in the database,
allowing developers to test the webhook simulator without needing a real
GitHub App connection.

Usage:
    python manage.py create_dev_github_repo --workspace 1 --repo owner/name

Only works when DEBUG=True.
"""

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError

from accounts.models import Workspace
from integrations.models import GitHubInstallation, GitHubRepository
from sources.models import Source


class Command(BaseCommand):
    help = "Create a fake GitHub repository for local development testing (DEBUG only)"

    def add_arguments(self, parser):
        parser.add_argument(
            "--workspace",
            type=str,
            required=True,
            help="Workspace ID or slug to add the repository to",
        )
        parser.add_argument(
            "--repo",
            type=str,
            required=True,
            help="Repository in owner/repo format (e.g., myorg/myrepo)",
        )
        parser.add_argument(
            "--private",
            action="store_true",
            default=False,
            help="Mark the repository as private",
        )

    def handle(self, *args, **options):
        if not settings.DEBUG:
            raise CommandError("This command only works in DEBUG mode. " "Set DJANGO_DEBUG=true in your environment.")

        workspace_id = options["workspace"]
        repo_full_name = options["repo"]
        is_private = options["private"]

        # Parse repo name
        if "/" not in repo_full_name:
            raise CommandError("--repo must be in owner/repo format")
        owner, name = repo_full_name.split("/", 1)

        # Find workspace
        try:
            # Try by ID first, then by slug
            try:
                workspace = Workspace.objects.get(pk=int(workspace_id))
            except (ValueError, Workspace.DoesNotExist):
                workspace = Workspace.objects.get(slug=workspace_id)
        except Workspace.DoesNotExist as err:
            raise CommandError(f"Workspace not found: {workspace_id}") from err

        # Create or get GitHubInstallation (fake one for dev)
        installation, inst_created = GitHubInstallation.objects.get_or_create(
            workspace=workspace,
            defaults={
                "installation_id": 999999999,  # Fake ID
                "account_login": f"dev-{workspace.slug}",
                "account_type": "Organization",
                "account_id": 999999999,
                "account_avatar_url": "https://avatars.githubusercontent.com/u/1?v=4",
                "permissions": {"issues": "write", "pull_requests": "write"},
            },
        )
        if inst_created:
            self.stdout.write(self.style.SUCCESS(f"Created fake GitHub installation for workspace: {workspace.slug}"))

        # Generate a deterministic fake repo_id from the name
        fake_repo_id = abs(hash(repo_full_name)) % 1000000000

        # Check if repo already exists
        existing = GitHubRepository.objects.filter(
            installation=installation,
            full_name=repo_full_name,
        ).first()

        if existing:
            if existing.is_archived:
                # Reactivate archived repo
                existing.is_archived = False
                existing.sync_status = "active"
                existing.save(update_fields=["is_archived", "sync_status", "updated_at"])
                self.stdout.write(self.style.SUCCESS(f"Reactivated existing repository: {repo_full_name}"))
            else:
                self.stdout.write(self.style.WARNING(f"Repository already exists: {repo_full_name}"))
            return

        # Create Source record
        source = Source.objects.create(
            workspace=workspace,
            name=repo_full_name,
            kind="github_repo",
            external_id=str(fake_repo_id),
            metadata={"owner": owner, "name": name, "dev_mode": True},
        )

        # Create GitHubRepository record
        GitHubRepository.objects.create(
            installation=installation,
            source=source,
            repo_id=fake_repo_id,
            owner=owner,
            name=name,
            full_name=repo_full_name,
            private=is_private,
            sync_status="active",  # Skip pending, it's fake
        )

        self.stdout.write(self.style.SUCCESS(f"\n✓ Created fake repository: {repo_full_name}"))
        self.stdout.write(f"  Workspace: {workspace.slug}")
        self.stdout.write(f"  Repo ID: {fake_repo_id}")
        self.stdout.write(f"  Private: {is_private}")
        self.stdout.write("")
        self.stdout.write("Now you can run the webhook simulator:")
        self.stdout.write(self.style.NOTICE(f"  python manage.py simulate_github_webhooks --repo {repo_full_name}"))
        self.stdout.write("")
        self.stdout.write("Or with Docker:")
        self.stdout.write(
            self.style.NOTICE(
                f"  docker compose --env-file .env -f infra/compose.dev.yaml exec api "
                f"python manage.py simulate_github_webhooks --repo {repo_full_name}"
            )
        )
