import secrets
import site
import sys
import textwrap

import pytest

from collections import defaultdict
from dataclasses import dataclass, field, asdict
from pathlib import Path
from typing import Any, List, Dict, Tuple
from unittest.mock import patch

from httpie.context import Environment
from httpie.compat import importlib_metadata
from httpie.status import ExitStatus
from httpie.plugins.manager import (
    enable_plugins,
    ENTRY_POINT_CLASSES as CLASSES,
)


def make_name() -> str:
    return 'httpie-' + secrets.token_hex(4)


@dataclass
class EntryPoint:
    name: str
    group: str

    def dump(self) -> Dict[str, str]:
        return asdict(self)


@dataclass
class Plugin:
    interface: 'Interface'

    name: str = field(default_factory=make_name)
    version: str = '1.0.0'
    entry_points: List[EntryPoint] = field(default_factory=list)

    def build(self) -> None:
        '''
        Create an installable dummy plugin at the given path.

        It will create a setup.py with the specified entry points,
        as well as dummy classes in a python module to imitate
        real plugins.
        '''

        groups = defaultdict(list)
        for entry_point in self.entry_points:
            groups[entry_point.group].append(entry_point.name)

        setup_eps = {
            group: [
                f'{name} = {self.import_name}:{name.title()}'
                for name in names
            ]
            for group, names in groups.items()
        }

        self.path.mkdir(parents=True, exist_ok=True)
        with open(self.path / 'setup.py', 'w') as stream:
            stream.write(textwrap.dedent(f'''
            from setuptools import setup

            setup(
                name='{self.name}',
                version='{self.version}',
                py_modules=['{self.import_name}'],
                entry_points={setup_eps!r},
                install_requires=['httpie']
            )
            '''))

        with open(self.path / (self.import_name + '.py'), 'w') as stream:
            stream.write('from httpie.plugins import *\n')