import click
import sys
import asyncio
from loguru import logger
from .client import SigaClient

@click.group()
@click.option('--username', envvar='SIGA_USERNAME', help='Siga username')
@click.option('--password', envvar='SIGA_PASSWORD', help='Siga password')
@click.option('--instituicao', envvar='SIGA_INSTITUICAO', help='Institution code')
@click.pass_context
def cli(ctx, username, password, instituicao):
    """Activesoft Siga CLI automation tool."""
    # Only enforce if a command is actually being run (not help)
    if ctx.invoked_subcommand and ctx.invoked_subcommand != 'help':
        if not username or not password or not instituicao:
            click.echo("Error: Username, password, and institution must be provided via arguments or environment variables.", err=True)
            ctx.exit(1)
    
    ctx.obj = SigaClient(username, password, instituicao)

async def run_async_command(client, coro):
    try:
        if await client.login():
            result = await coro
            return result
    finally:
        await client.client.aclose()

@cli.command()
@click.option('--limit', default=10, help='Number of students to list')
@click.option('--id', 'student_id', type=int, help='Fetch details for a specific student ID')
@click.pass_obj
def students(client, limit, student_id):
    """List students or fetch specific detail."""
    async def run():
        if student_id:
            data = await client.get_aluno_detail(student_id)
            student_info = data.get('aluno', data)
            logger.info(f"Detailed Student Data: {student_info}")
        else:
            data = await client.list_alunos(limit=limit)
            results = data.get('results', [])
            for student in results:
                logger.info(f"ID: {student.get('id')} | Name: {student.get('nome')}")
    
    try:
        asyncio.run(run_async_command(client, run()))
    except Exception as e:
        logger.exception(f"An error occurred: {e}")
        sys.exit(1)

@cli.command()
@click.option('--limit', default=21, help='Number of responsible parties to list')
@click.option('--id', 'responsavel_id', type=int, help='Fetch details for a specific responsible party ID')
@click.pass_obj
def responsaveis(client, limit, responsavel_id):
    """List responsible parties (guardians) or fetch specific detail."""
    async def run():
        if responsavel_id:
            data = await client.get_responsavel_detail(responsavel_id)
            resp_info = data.get('responsavel', data)
            logger.info(f"Detailed Responsible Data: {resp_info}")
        else:
            data = await client.list_responsaveis(limit=limit)
            results = data.get('results', [])
            for resp in results:
                logger.info(f"ID: {resp.get('id')} | Name: {resp.get('nome')}")

    try:
        asyncio.run(run_async_command(client, run()))
    except Exception as e:
        logger.exception(f"An error occurred: {e}")
        sys.exit(1)

@cli.command()
@click.option('--student-id', required=True, type=int, help='Standard student ID')
@click.option('--destinatario-id', required=True, type=int, help='Recipient ID (e.g. parent)')
@click.option('--message', required=True, help='Message text')
@click.option('--title', default="Aviso", help='Message title')
@click.option('--type', default="R", help='Recipient type (R for responsible)')
@click.option('--origem', default=2, type=int, help='Origin code')
@click.pass_obj
def send_message(client, student_id, destinatario_id, message, title, type, origem):
    """Send a message to a student/responsible party."""
    async def run():
        result = await client.send_message(
            student_id=student_id,
            destinatario_id=destinatario_id,
            message_text=message,
            message_title=title,
            destinatario_tipo=type,
            origem=origem
        )
        logger.info(f"Message send result: {result}")
        
    try:
        asyncio.run(run_async_command(client, run()))
    except Exception as e:
        logger.exception(f"An error occurred: {e}")
        sys.exit(1)

def main():
    cli()

if __name__ == "__main__":
    main()
