#!/usr/bin/env python3
# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""
Plugin Template Generator

Create a new plugin with the standard structure.

Usage:
    python -m familiar.create_plugin my-awesome-plugin
"""

import argparse
from pathlib import Path

SKILL_TEMPLATE = '''"""
{name} Skill

{description}
"""

import logging

logger = logging.getLogger(__name__)


def example_function(data: dict) -> str:
    """
    Example tool function.

    Args:
        data: Tool input parameters

    Returns:
        Result string
    """
    param = data.get("param", "default")

    # TODO: Implement your logic here

    return f"Result: {{param}}"


# Tool definitions - the agent will discover these automatically
TOOLS = [
    {{
        "name": "{id}_example",
        "description": "Example tool for {name}",
        "input_schema": {{
            "type": "object",
            "properties": {{
                "param": {{
                    "type": "string",
                    "description": "Example parameter"
                }}
            }},
            "required": ["param"]
        }},
        "handler": example_function,
        "category": "{id}"
    }}
]
'''

SKILL_MD_TEMPLATE = """# {name}

{description}

## Usage

- "Example command using {name}"

## Setup

1. Install the plugin: `install plugin {id}`
2. Configure any required settings
3. Start using!

## Tools

### {id}_example
Example tool description.

**Parameters:**
- `param` (required): Example parameter

## Configuration

Set these environment variables if needed:
- `{env_prefix}_API_KEY`: Your API key
"""

README_TEMPLATE = """# {name}

{description}

## Installation

```bash
# Via Familiar
"Install the {id} plugin"

# Or manually
git clone {repo_url}
cd {id}
pip install -r requirements.txt
```

## Usage

Once installed, you can use natural language:
- "Example command"

## Development

1. Clone this repo
2. Install dependencies: `pip install -r requirements.txt`
3. Edit `skill.py` to add your tools
4. Test locally

## License

MIT
"""

REQUIREMENTS_TEMPLATE = """# {name} dependencies
# Add your Python dependencies here
# requests>=2.28.0
"""


def create_plugin(name: str, path: str = None, description: str = None):
    """Create a new plugin from template."""

    # Normalize plugin ID
    plugin_id = name.lower().replace(" ", "-").replace("_", "-")
    plugin_name = name.replace("-", " ").replace("_", " ").title()

    # Determine path
    if path:
        plugin_path = Path(path)
    else:
        plugin_path = Path.cwd() / plugin_id

    if plugin_path.exists():
        print(f"❌ Directory already exists: {plugin_path}")
        return False

    description = description or f"A Familiar plugin for {plugin_name}"
    env_prefix = plugin_id.upper().replace("-", "_")

    # Create directory
    plugin_path.mkdir(parents=True)

    # Create files
    (plugin_path / "skill.py").write_text(
        SKILL_TEMPLATE.format(name=plugin_name, id=plugin_id, description=description)
    )

    (plugin_path / "SKILL.md").write_text(
        SKILL_MD_TEMPLATE.format(
            name=plugin_name, id=plugin_id, description=description, env_prefix=env_prefix
        )
    )

    (plugin_path / "README.md").write_text(
        README_TEMPLATE.format(
            name=plugin_name,
            id=plugin_id,
            description=description,
            repo_url=f"https://github.com/YOUR_USERNAME/{plugin_id}",
        )
    )

    (plugin_path / "requirements.txt").write_text(REQUIREMENTS_TEMPLATE.format(name=plugin_name))

    # Create __init__.py
    (plugin_path / "__init__.py").write_text(f'"""{plugin_name} Plugin"""\n')

    print(f"""
✅ Created plugin: {plugin_name}

Directory: {plugin_path}

Files created:
  • skill.py         - Your tool implementations
  • SKILL.md         - User documentation
  • README.md        - Repository README
  • requirements.txt - Python dependencies
  • __init__.py      - Package init

Next steps:
  1. Edit skill.py to add your tools
  2. Add dependencies to requirements.txt
  3. Update documentation in SKILL.md
  4. Push to GitHub
  5. Add to the plugin registry (or install locally)

To install locally:
  ln -s {plugin_path} ~/.familiar/skills/{plugin_id}
""")

    return True


def main():
    parser = argparse.ArgumentParser(description="Create a new Familiar plugin")
    parser.add_argument("name", help="Plugin name (e.g., 'my-cool-plugin')")
    parser.add_argument("--path", "-p", help="Output directory")
    parser.add_argument("--description", "-d", help="Plugin description")

    args = parser.parse_args()

    create_plugin(args.name, args.path, args.description)


if __name__ == "__main__":
    main()
