from pathlib import Path

import click
from loguru import logger

try:
    LOG_DIR = Path.home() / '.phone-copilot'
    logger.add(LOG_DIR / 'log.log', rotation='10 MB')
except Exception as e:  # noqa: BLE001
    logger.error(f'Failed to set up logger directory: {e}')


@click.command()
@click.argument('task', required=True)
@click.option('--base-url', required=True, help='The base URL of the model API.')
@click.option('--model', required=True, help='The name of the model to use.')
@click.option('--api-key', default='', help='The API key for authentication with the model API.')
@click.option(
    '--device', '-d', help='The ID of the target device. If not specified, the first connected device will be used.'
)
@click.option(
    '--lang', '-l', default='zh', type=click.Choice(['zh', 'en']), help='The language for system prompts (zh or en).'
)
@click.option('--max-steps', default=100, help='The maximum number of steps the agent can take before giving up.')
@click.option(
    '--ccf',
    default=1000,
    help='Context Compression Factor for the agent. Like QWen Model, it should be set to 0. AutoGLM Model should be set to 1000.',  # noqa: E501
)
@click.option('--json', help='The json report file path to save the execution details.')
@click.option('--html', help='The html report file path to save the execution details.')
@click.option(
    '--adb-keyboard',
    is_flag=True,
    default=False,
    help='Enable ADB keyboard input method with the specified keyboard ID',
)
def main(
    task: str,
    base_url: str,
    model: str,
    api_key: str,
    device: str,
    lang: str,
    max_steps: int,
    ccf: int,
    json: str,
    html: str,
    adb_keyboard: bool,  # noqa: FBT001
) -> None:
    from phone_copilot.api import run_task

    agent = run_task(
        task=task,
        base_url=base_url,
        model=model,
        api_key=api_key,
        device=device,
        language=lang,
        max_steps=max_steps,
        ccf=ccf,
        adb_keyboard=adb_keyboard,
    )

    if json:
        agent.export_json(Path(json).with_suffix('.json'))

    if html:
        agent.export_html(Path(html).with_suffix('.html'))


if __name__ == '__main__':
    main()
