"""Example usage of the Questra Automation client."""

from questra_authentication import QuestraAuthentication

from questra_automation import (
    ExecutionInitiator,
    QuestraAutomation,
    RepositoryAuthenticationMethod,
)

# Create QuestraAuthentication
auth_client = QuestraAuthentication(
    url="https://authentik.dev.example.com",
    username="ServiceUser",
    password="secret_password",
    oidc_discovery_paths=["/application/o/automation"],
)

# Initialize QuestraAutomation
client = QuestraAutomation(
    graphql_url="https://automation.dev.example.com/graphql",
    auth_client=auth_client,
)

# ===== Query Examples =====

# Get service info
service_info = client.queries.get_service_info()
print(f"Service: {service_info.name} v{service_info.version}")

# Get workspaces
workspaces = client.queries.get_workspaces(first=10)
print(f"\nTotal workspaces: {workspaces.total_count}")
for workspace in workspaces.nodes:
    print(f"  - {workspace.name} (Status: {workspace.build_status.value})")

# Get automations with filter
automations = client.queries.get_automations(
    first=10, where={"workspaceName": {"eq": "my-workspace"}}
)
print(f"\nAutomations in 'my-workspace': {automations.total_count}")
for automation in automations.nodes:
    print(f"  - {automation.path}")

# Get executions with filter and sorting
executions = client.queries.get_executions(
    first=10,
    where={"status": {"eq": "SUCCEEDED"}},
    order=[{"createdAt": "DESC"}],
)
print(f"\nSuccessful executions: {executions.total_count}")
for execution in executions.nodes:
    print(
        f"  - {execution.automation_path} "
        f"(Status: {execution.status.value}, Created: {execution.created_at})"
    )

# Get repositories
repositories = client.queries.get_repositories(first=10)
print(f"\nRepositories: {repositories.total_count}")
for repo in repositories.nodes:
    print(f"  - {repo.name} ({repo.url})")

# Get schedules
schedules = client.queries.get_schedules(first=10)
print(f"\nSchedules: {schedules.total_count}")
for schedule in schedules.nodes:
    print(
        f"  - {schedule.name} "
        f"(Active: {schedule.active}, Cron: {schedule.cron})"
    )

# Get scheduled executions
from datetime import datetime, timedelta

now = datetime.now()
next_week = now + timedelta(days=7)
scheduled_execs = client.queries.get_scheduled_executions(
    from_time=now, to_time=next_week, first=10
)
print(f"\nScheduled executions in next 7 days: {len(scheduled_execs.nodes)}")
for sched_exec in scheduled_execs.nodes:
    print(
        f"  - {sched_exec.automation_path} "
        f"(Fire time: {sched_exec.fire_time})"
    )

# Get error codes
error_codes = client.queries.get_error_codes(first=10)
print(f"\nError codes: {error_codes.total_count}")
for error_code in error_codes.nodes:
    print(f"  - {error_code.code}: {error_code.message_template}")

# ===== Mutation Examples =====

# Execute an automation
execution_result = client.mutations.execute_automation(
    workspace_name="my-workspace",
    automation_path="scripts/my_automation.py",
    initiator_type=ExecutionInitiator.MANUAL,
    arguments=[
        {"name": "environment", "value": "production"},
        {"name": "verbose", "value": "true"},
    ],
)
print(f"\nExecution started with ID: {execution_result.id}")

# Create a repository
repo_result = client.mutations.create_repository(
    name="my-repo",
    url="https://github.com/example/my-repo.git",
    credentials_method=RepositoryAuthenticationMethod.SSH_KEY,
)
print(f"\nRepository created: {repo_result.name}")

# Create a workspace
workspace_result = client.mutations.create_workspace(
    repository_name="my-repo",
    name="my-workspace",
    branch_name="main",
    commit="abc123def456",
)
print(f"\nWorkspace created: {workspace_result.name}")

# Create a schedule
schedule_result = client.mutations.create_schedule(
    workspace_name="my-workspace",
    automation_path="scripts/daily_task.py",
    name="daily-task",
    description="Run daily at midnight",
    cron="0 0 * * *",
    timezone="Europe/Berlin",
    active=True,
    arguments=[{"name": "environment", "value": "production"}],
)
print(
    f"\nSchedule created: {schedule_result.name} "
    f"for {schedule_result.automation_path}"
)

# Update a schedule
update_schedule_result = client.mutations.update_schedule(
    workspace_name="my-workspace",
    automation_path="scripts/daily_task.py",
    name="daily-task",
    active=False,
)
print(f"\nSchedule updated: {update_schedule_result.name}")

# Synchronize workspace
sync_result = client.mutations.synchronize_workspace(name="my-workspace")
print(f"\nWorkspace synchronized: {sync_result.name}")

# Renew SSH key
renew_result = client.mutations.renew_repository_ssh_key(name="my-repo")
print(f"\nSSH key renewed for: {renew_result.name}")

# Delete a schedule
delete_schedule_result = client.mutations.delete_schedule(
    workspace_name="my-workspace",
    automation_path="scripts/daily_task.py",
    name="daily-task",
)
print(f"\nSchedule deleted: {delete_schedule_result.name}")

# Delete a workspace
delete_workspace_result = client.mutations.delete_workspace(name="my-workspace")
print(f"\nWorkspace deleted: {delete_workspace_result.name}")

# Delete a repository
delete_repo_result = client.mutations.delete_repository(name="my-repo")
print(f"\nRepository deleted: {delete_repo_result.name}")

# ===== Raw Query Example =====

# Execute a raw GraphQL query
raw_result = client.execute_raw(
    """
    query {
        automationServiceInfo {
            name
            version
            informationalVersion
        }
    }
    """
)
print(f"\nRaw query result: {raw_result}")
