#!/usr/bin/env python3
"""Run Step 1 and Step 2 workflows in the required order."""

import argparse

import fuente_prospecto_workflow
import tag_canal_origen_workflow


def main():
    parser = argparse.ArgumentParser(description="Run GHL origen/fuente workflows in order")
    parser.add_argument("--location", help="Specific location ID to process")
    parser.add_argument("--all", action="store_true", help="Process all branch locations from the CSV")
    parser.add_argument("--include-main", action="store_true", help="Include the main brand account when using --all")
    parser.add_argument("--dry-run", action="store_true", help="Preview changes without writing to GHL")
    parser.add_argument("--contact-only", action="store_true", help="Step 1 only updates contacts, not opportunities")
    parser.add_argument("--no-skip", action="store_true", help="Step 2 updates even if Fuente de Prospecto already matches")
    parser.add_argument("--sync-main", action="store_true", help="Also sync exact matching records in the main brand account")
    parser.add_argument("--run-id", help="Audit run ID supplied by the dashboard")
    args = parser.parse_args()

    accounts = tag_canal_origen_workflow.select_locations(args)

    print("\n" + "#" * 60)
    print("STEP 1/2 - TAG -> CANAL DE ORIGEN")
    print("#" * 60)
    total_step_1 = 0
    for account in accounts:
        try:
            total_step_1 += tag_canal_origen_workflow.process_location(
                account,
                dry_run=args.dry_run,
                contact_only=args.contact_only,
                run_id=args.run_id,
                sync_main=args.sync_main,
            )
        except Exception as exc:
            print(f"\nERROR {account['nombre']} in Step 1: {exc}")

    print("\n" + "#" * 60)
    print("STEP 2/2 - CANAL DE ORIGEN -> FUENTE DE PROSPECTO")
    print("#" * 60)
    total_step_2 = 0
    for account in accounts:
        try:
            total_step_2 += fuente_prospecto_workflow.process_location(
                account,
                dry_run=args.dry_run,
                skip_correct=not args.no_skip,
                run_id=args.run_id,
                sync_main=args.sync_main,
            )
        except Exception as exc:
            print(f"\nERROR {account['nombre']} in Step 2: {exc}")

    print("\n" + "=" * 60)
    print(f"DONE - Step 1 contacts: {total_step_1}, Step 2 contacts: {total_step_2}")


if __name__ == "__main__":
    main()
