import argparse
import asyncio
import logging
import warnings
from pathlib import Path

from app.context import Context, watch_files_and_sync_states
from app.settings import setup_app

warnings.filterwarnings("ignore", message="urllib3|chardet|charset_normalizer")


from app.settings import Setup  # noqa: E402

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.getLogger("httpx").setLevel(logging.WARNING)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--clear-data",
        action="store_true",
        help="Limpa histórico de usuários e skills antes de iniciar",
    )

    parser.add_argument(
        "--save-requests",
        action="store_true",
        help="Salva conteúdo das requisições ao provedor na pasta `requests/`",
    )

    subparsers = parser.add_subparsers(dest="channel", required=True)

    subparsers.add_parser("telegram", help="Executa o bot do Telegram")
    subparsers.add_parser("whatsapp", help="Executa o bot do WhatsApp")

    web_parser = subparsers.add_parser(
        "web", help="Interface web para debug (apenas desenvolvimento)"
    )
    web_parser.add_argument(
        "--port", type=int, default=7932, help="Porta do servidor web (padrão: 7932)"
    )

    args = parser.parse_args()

    return args


def clear_data(setup: Setup) -> None:
    setup.clear_data()
    logger.info("Os dados do app foram limpos com sucesso.")


async def start_app(ctx: Context, channel: str, save_requests_dir: Path | None) -> None:
    asyncio.create_task(watch_files_and_sync_states(ctx))

    from app.agent import create_reactive_chat_agent

    reactive_agent = create_reactive_chat_agent(ctx, save_requests_dir)

    if channel == "telegram":
        from app.channels.telegram import run_telegram_bot

        await run_telegram_bot(ctx, reactive_agent)

    elif channel == "whatsapp":
        from app.channels.whatsapp import run_whatsapp_bot

        await run_whatsapp_bot(ctx, reactive_agent)


async def start_web_app(ctx: Context, port: int) -> None:
    import uvicorn

    from app.agent import build_dependencies, create_chat_agent
    from app.models import build_primary_model

    primary_model = build_primary_model(ctx.settings.get())
    agent = create_chat_agent(ctx, model=primary_model)
    deps = build_dependencies(ctx, user_id="dev")
    web_app = agent.to_web(deps=deps)

    logger.info("Interface web disponível em http://127.0.0.1:%d", port)
    config = uvicorn.Config(web_app, host="127.0.0.1", port=port, log_level="warning")
    server = uvicorn.Server(config)
    await server.serve()


def main() -> None:
    args = parse_args()
    paths, settings, contacts, prompt = setup_app(clear_data=args.clear_data)
    save_requests_dir = paths.saved_requests_directory if args.save_requests else None
    app_context = Context(paths, settings, contacts, prompt)

    if args.channel == "web":
        asyncio.run(start_web_app(app_context, port=args.port))
    else:
        asyncio.run(start_app(app_context, args.channel, save_requests_dir))


if __name__ == "__main__":
    main()
