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
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
import asyncio
import gradio as gr # Added Gradio import
from telethon import TelegramClient, functions
from telethon.errors import SessionPasswordNeededError, FloodWaitError, PhoneCodeInvalidError, PasswordHashInvalidError # Added specific exceptions
from telethon.tl.types import PeerUser, PeerChat, PeerChannel, DialogFilter
import getpass # Still needed for 2FA password (though Gradio will handle input)
import os
import json # Import the json module
import re # For sanitizing filenames
import time # For handling rate limits
from datetime import datetime, timezone # Import timezone
from telethon.tl.types import InputPeerUser
import csv

CONFIG_FILE = 'config.json'
BASE_OUTPUT_DIR = 'folder_downloads' # Base directory to store folder downloads
# Dictionary to store fetched filter objects for later peer retrieval - Needs careful state management with Gradio
# fetched_filters = {} # Will be managed via gr.State

# --- Configuration Functions (Mostly unchanged) ---
def load_config():
    """Loads configuration from the JSON file."""
    if os.path.exists(CONFIG_FILE):
        try:
            with open(CONFIG_FILE, 'r') as f:
                return json.load(f)
        except json.JSONDecodeError:
            print(f"Warning: Error reading {CONFIG_FILE}. Will re-prompt for details.")
            return {}
        except Exception as e:
            print(f"Warning: Could not load config file {CONFIG_FILE}: {e}")
            return {}
    return {}

def save_config(config_data):
    """Saves configuration to the JSON file."""
    try:
        with open(CONFIG_FILE, 'w') as f:
            json.dump(config_data, f, indent=4)
        # No print here, output goes to Gradio UI
    except Exception as e:
        # Log error to Gradio UI
        print(f"Error saving config file {CONFIG_FILE}: {e}") # Keep console print for now
        return f"Error saving config file: {e}"
    return "Configuration saved."

def sanitize_filename(name):
    """Removes invalid characters for filenames."""
    name = str(name) # Ensure it's a string
    name = re.sub(r'[^\w\-\s]', '', name)
    name = name.replace(' ', '_')
    name = re.sub(r'_+', '_', name)
    name = name.strip('_')
    return name[:100] if name else "unnamed_chat"

# --- Refactored Core Logic for Gradio ---

# Placeholder for client state - managed by Gradio
# client = None
# sent_code_info = None # Store phone_code_hash

async def connect_and_authenticate(api_id_str, api_hash, phone_number):
    """Attempts to connect and initiate authentication."""
    # Use client and sent_code_info carefully - Gradio State is preferred
    client = None
    sent_code_info = None

    if not api_id_str or not api_hash or not phone_number:
        yield "API ID, API Hash, and Phone Number are required."
        yield (None, None, None, "Error") # Yield final state tuple
        return

    if not api_id_str.isdigit():
        yield "Invalid API ID. Please enter a number."
        yield (None, None, None, "Error")
        return

    api_id = int(api_id_str)
    safe_phone = ''.join(filter(str.isalnum, phone_number))
    session_file = f'{safe_phone}_session'
    client = TelegramClient(session_file, api_id, api_hash)
    sent_code_info = None # Reset sent code info

    yield "Connecting to Telegram..."
    try:
        await client.connect()
    except Exception as e:
        yield f"Failed to connect: {e}"
        yield (None, None, None, "Error")
        return # Use bare return after yielding final state

    if await client.is_user_authorized():
        yield "Already authorized."
        # Save config if details were manually entered
        config = load_config()
        if str(config.get('api_id')) != api_id_str or config.get('api_hash') != api_hash or config.get('phone_number') != phone_number:
             config['api_id'] = api_id_str
             config['api_hash'] = api_hash
             config['phone_number'] = phone_number
             save_status = save_config(config)
             yield save_status

        yield (client, None, None, "Authorized") # Yield final state
        return
    else:
        yield "Authorization needed. Sending code..."
        try:
            sent_code_info = await client.send_code_request(phone_number)
            yield "Code sent. Please enter the code below."
            yield (client, sent_code_info, None, "NeedCode") # Yield final state
            return
        except FloodWaitError as fwe:
             yield f"Rate limit hit. Please wait {fwe.seconds} seconds and try connecting again."
             if client and client.is_connected():
                 await client.disconnect()
             yield (None, None, None, "Error")
             return
        except Exception as e:
             yield f"Error sending code: {e}"
             if client and client.is_connected():
                 await client.disconnect()
             yield (None, None, None, "Error")
             return

async def submit_telegram_code(current_client, current_sent_code_info, phone_number, code):
    """Submits the Telegram code."""
    if not current_client or not code:
        yield "Connection not established or code missing."
        yield (current_client, current_sent_code_info, "Error")
        return

    try:
        await current_client.sign_in(phone_number, code, phone_code_hash=getattr(current_sent_code_info, 'phone_code_hash', None))
        yield "Signed in successfully!"
         # Save config since authentication succeeded
        config = load_config()
        config['api_id'] = str(current_client.api_id)
        config['api_hash'] = current_client.api_hash
        config['phone_number'] = phone_number
        save_status = save_config(config)
        yield save_status
        yield (current_client, None, "Authorized") # Yield final state
        return
    except PhoneCodeInvalidError:
        yield "Invalid code. Please try again."
        yield (current_client, current_sent_code_info, "NeedCode")
        return
    except SessionPasswordNeededError:
        yield "Two-factor authentication enabled. Please enter your password."
        yield (current_client, None, "NeedPassword")
        return
    except FloodWaitError as fwe:
        yield f"Rate limit hit. Waiting {fwe.seconds} seconds..."
        await asyncio.sleep(fwe.seconds)
        yield "Wait finished. Please try submitting the code again."
        yield (current_client, current_sent_code_info, "NeedCode")
        return
    except Exception as e:
        yield f"Error during sign in: {e}"
        # Consider disconnecting or letting user retry
        yield (current_client, current_sent_code_info, "NeedCode") # Let user retry
        return

async def submit_telegram_password(current_client, password):
    """Submits the Telegram 2FA password."""
    if not current_client or not password:
        yield "Connection not established or password missing."
        yield (current_client, "Error")
        return

    try:
        await current_client.sign_in(password=password)
        yield "Signed in successfully with password!"
        # Config should have been saved during connect/code phases if needed
        yield (current_client, "Authorized")
        return
    except PasswordHashInvalidError:
        yield "Invalid password. Please try again."
        yield (current_client, "NeedPassword")
        return
    except FloodWaitError as fwe:
        yield f"Rate limit hit. Waiting {fwe.seconds} seconds..."
        await asyncio.sleep(fwe.seconds)
        yield "Wait finished. Please try submitting the password again."
        yield (current_client, "NeedPassword")
        return
    except Exception as e:
        yield f"Failed 2FA sign in: {e}"
        # Consider disconnecting or letting user retry
        yield (current_client, "NeedPassword") # Let user retry
        return

async def get_folders(current_client):
    """Fetches chat folders and returns a list for display and fetched filter objects."""
    if not current_client or not await current_client.is_user_authorized():
        yield "Client not connected or authorized." # Yield message first
        yield ([], {}, "Client not connected or authorized.") # Then yield state tuple
        return # Bare return

    yield "Fetching chat folders..."
    folders_for_display = []
    local_fetched_filters = {} # Store filters locally for this call

    try:
        # Add default folders (optional, might not be needed if only downloading custom)
        # folders_for_display.append({"id": 0, "title": "All Chats"}) # ID 0 not usable?
        # folders_for_display.append({"id": 1, "title": "Archived Chats"}) # ID 1 not usable?

        result = await current_client(functions.messages.GetDialogFiltersRequest())

        for f in result.filters:
            if isinstance(f, DialogFilter):
                # Get the title from TextWithEntities if present
                if hasattr(f, 'title') and hasattr(f.title, 'text'):
                    folder_title = f.title.text
                else:
                    folder_title = getattr(f, 'title', '') # Use getattr for safety
                # Telethon sometimes returns non-string titles directly
                if not isinstance(folder_title, str):
                     folder_title = f"Folder_{f.id}" # Fallback

                if f.id >= 2: # Only custom folders seem reliably usable for peer lists
                     display_text = f"{folder_title} (ID: {f.id})"
                     folders_for_display.append((display_text, f.id)) # Tuple for Gradio Dropdown (display_text, value)
                     local_fetched_filters[f.id] = f

        if not local_fetched_filters:
            yield "No custom chat folders found."
            yield ([], {}, "No custom folders.") # Yield tuple
            return # Add return
        else:
            yield f"Found {len(local_fetched_filters)} custom folder(s)."
             # Sort by ID for consistency
            try:
                 # Safer sorting in case title format is unexpected
                 folders_for_display.sort(key=lambda x: int(re.search(r'\(ID:\s*(\d+)\)', x[0]).group(1)) if re.search(r'\(ID:\s*(\d+)\)', x[0]) else f.id)
            except Exception:
                 pass # Ignore sorting errors if regex fails
            yield (folders_for_display, local_fetched_filters, "Folders fetched.") # Yield tuple
            return # Add return

    except FloodWaitError as fwe:
        yield f"Rate limit hit fetching folders. Waiting {fwe.seconds} seconds..."
        await asyncio.sleep(fwe.seconds)
        yield "Wait finished. Try fetching folders again."
        yield ([], {}, "Rate limit error.") # Yield tuple
        return # Add return
    except Exception as e:
        yield f"An error occurred while fetching folders: {e}"
        yield ([], {}, f"Error fetching folders: {e}") # Yield tuple
        return # Add return


async def export_folder_peers(current_client, folder_id, folder_title, current_fetched_filters):
    """Exports peers from the selected folder to a CSV file."""
    if not current_client or not folder_id or not current_fetched_filters:
        yield "Client not ready, folder not selected, or filter data missing."
        return

    selected_filter_object = current_fetched_filters.get(int(folder_id))

    if selected_filter_object and hasattr(selected_filter_object, 'include_peers') and selected_filter_object.include_peers:
        yield f"Exporting included users/chats for folder '{folder_title}'..."
        sanitized_title = sanitize_filename(folder_title)
        # Ensure BASE_OUTPUT_DIR exists
        os.makedirs(BASE_OUTPUT_DIR, exist_ok=True)
        # Place CSV inside the base output dir
        csv_filename = os.path.join(BASE_OUTPUT_DIR, f"folder_{sanitized_title}_users_chats.csv")


        peers_exported_count = 0
        try:
            with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow(['Type', 'ID', 'Username', 'Display Name', 'Full Name', 'Phone'])

                for peer_input in selected_filter_object.include_peers:
                    try:
                        # Using get_input_entity to handle various peer types potentially more robustly
                        input_peer = await current_client.get_input_entity(peer_input)
                        # Then get the full entity details
                        entity = await current_client.get_entity(input_peer)

                        entity_type = type(entity).__name__
                        username = getattr(entity, 'username', '') or ''
                        display_name = getattr(entity, 'title', None) or getattr(entity, 'username', None) or getattr(entity, 'first_name', f"ID: {entity.id}")
                        if not display_name and hasattr(entity, 'first_name'): # Handle users better
                             display_name = entity.first_name + (f" {entity.last_name}" if getattr(entity, 'last_name', None) else "")

                        full_name = (getattr(entity, 'first_name', '') or '') + ' ' + (getattr(entity, 'last_name', '') or '')
                        full_name = full_name.strip()
                        phone = getattr(entity, 'phone', '') or ''

                        writer.writerow([
                            entity_type,
                            entity.id,
                            username,
                            display_name,
                            full_name if full_name else display_name, # Use display_name if full_name is empty
                            phone
                        ])
                        peers_exported_count += 1
                        # Yield progress? Maybe too noisy.
                        # yield f"  - Exported: {display_name}"
                    except ValueError:
                         yield f"  - Warning: Could not resolve peer: {peer_input}. Might be inaccessible."
                    except FloodWaitError as fwe_peer:
                         yield f"  ! Rate limit hit exporting peer {peer_input}. Waiting {fwe_peer.seconds} seconds..."
                         await asyncio.sleep(fwe_peer.seconds + 2)
                         yield f"  ! Retrying peer export for {peer_input}..."
                         # Simple retry logic (could be improved)
                         try:
                              input_peer = await current_client.get_input_entity(peer_input)
                              entity = await current_client.get_entity(input_peer)
                              # ... (repeat export logic - better to refactor into a function)
                              yield f"  - Successfully exported after wait: {getattr(entity, 'title', entity.id)}"
                         except Exception as e_retry:
                              yield f"  - Warning: Still could not process peer {peer_input} after retry: {e_retry}"
                    except Exception as e_peer:
                         yield f"  - Warning: Error processing peer {peer_input}: {e_peer}"

            if peers_exported_count > 0:
                 yield f"Successfully exported details for {peers_exported_count} users/chats to {csv_filename}"
            else:
                 yield f"No exportable users/chats found or processed in folder '{folder_title}'. CSV not created or is empty."
                 # No need to delete, as we only create if count > 0 (or handle empty file if created initially)
                 if os.path.exists(csv_filename):
                     try:
                         # Check if file is truly empty (besides header)
                         if os.path.getsize(csv_filename) <= 100: # Allow for header size
                             os.remove(csv_filename)
                             yield f"Removed empty/header-only file: {csv_filename}"
                     except OSError:
                          pass # Ignore if removal fails

        except IOError as e_csv:
            yield f"Error writing CSV file {csv_filename}: {e_csv}"
    elif selected_filter_object:
         yield f"Folder '{folder_title}' does not seem to contain specific included peers."
    else:
         yield f"Could not find filter details for folder ID {folder_id}."


async def download_messages_for_folder(current_client, folder_id, folder_title, current_fetched_filters, message_limit_str):
    """Downloads messages for all peers included in the selected folder."""
    if not current_client or not folder_id or not current_fetched_filters:
        yield "Client not ready, folder not selected, or filter data missing."
        return

    selected_filter_object = current_fetched_filters.get(int(folder_id))
    if not selected_filter_object or not hasattr(selected_filter_object, 'include_peers') or not selected_filter_object.include_peers:
        yield f"No specific peers found to download for folder '{folder_title}'. Export skipped or folder doesn't define included peers."
        return

    try:
        message_limit = int(message_limit_str) if message_limit_str and message_limit_str.isdigit() else None
        limit_text = f" (Limit: {message_limit})" if message_limit else " (Limit: All)"
        yield f"Starting download for folder '{folder_title}'{limit_text}..."
    except ValueError:
        yield "Invalid Message Limit. Please enter a number or leave blank for all."
        message_limit = None
        limit_text = " (Limit: All)"
        yield f"Proceeding with Limit: All..."


    sanitized_folder_title = sanitize_filename(folder_title)
    folder_output_dir = os.path.join(BASE_OUTPUT_DIR, sanitized_folder_title)
    os.makedirs(folder_output_dir, exist_ok=True)
    yield f"Output directory: {folder_output_dir}"

    download_count = 0
    error_count = 0

    for peer_input in selected_filter_object.include_peers:
        entity = None
        entity_display_name = f"Peer {peer_input}" # Default name
        try:
            # Resolve peer first
            input_peer = await current_client.get_input_entity(peer_input)
            entity = await current_client.get_entity(input_peer)
            entity_display_name = getattr(entity, 'title', None) or getattr(entity, 'username', None) or getattr(entity, 'first_name', f"ID: {entity.id}")
            if not entity_display_name and hasattr(entity, 'first_name'):
                 entity_display_name = entity.first_name + (f" {entity.last_name}" if getattr(entity, 'last_name', None) else "")

            sanitized_entity_name = sanitize_filename(entity_display_name if entity_display_name else f"chat_{entity.id}")
            output_filename = f"{sanitized_entity_name}_messages.txt"
            output_filepath = os.path.join(folder_output_dir, output_filename)

            yield f"  -> Downloading messages for: {entity_display_name} (ID: {entity.id})..."

            messages_data = []
            msg_count = 0
            download_start_time = time.time()

            async for message in current_client.iter_messages(entity, limit=message_limit):
                sender = await message.get_sender()
                sender_name = "Unknown/Channel"
                sender_id_str = "N/A"
                if sender:
                    sender_id_str = str(sender.id)
                    sender_name = getattr(sender, 'username', None) or \
                                  (getattr(sender, 'first_name', '') + (' ' + getattr(sender, 'last_name', '') if getattr(sender, 'last_name', None) else '')).strip() or \
                                  f"User ID {sender.id}" # Fallback sender name

                timestamp_str = "Invalid Date"
                if message.date:
                    # Convert to local timezone for display if desired, otherwise keep UTC
                    # local_dt = message.date.astimezone()
                    # timestamp_str = local_dt.strftime('%Y-%m-%d %H:%M:%S %Z')
                    timestamp_str = message.date.strftime('%Y-%m-%d %H:%M:%S UTC')


                text = message.text or "[Media/Other]"
                # Include message ID for reference
                message_info = f"[{timestamp_str} MID: {message.id}] {sender_name} (UID: {sender_id_str}):\n{text}\n{'-'*20}"
                messages_data.append(message_info)
                msg_count += 1

                # Progress update within a chat download (optional, can be slow)
                # if msg_count % 100 == 0:
                #    yield f"     Downloaded {msg_count} messages for {entity_display_name}..."

            download_end_time = time.time()
            duration = download_end_time - download_start_time

            if messages_data:
                yield f"  -> Finished downloading {len(messages_data)} messages for {entity_display_name} in {duration:.2f}s."
                yield f"  -> Saving messages to {output_filepath}..."
                try:
                    with open(output_filepath, 'w', encoding='utf-8') as f:
                        f.write(f"Messages from: {entity_display_name}\n")
                        f.write(f"Entity ID: {entity.id}\n")
                        f.write(f"Total messages downloaded (limit={message_limit if message_limit else 'All'}): {len(messages_data)}\n")
                        f.write("="*40 + "\n\n")
                        for msg_info in reversed(messages_data): # Save oldest first
                            f.write(msg_info + '\n\n')
                    yield f"  -> Messages for {entity_display_name} saved successfully."
                    download_count += 1
                except IOError as e_write:
                     yield f"  ! Error writing file {output_filepath}: {e_write}"
                     error_count += 1
            else:
                yield f"  -> No messages found or downloaded for {entity_display_name}."
                # Optionally delete empty file placeholder if created

        except FloodWaitError as fwe:
            yield f"  ! Rate limit hit for {entity_display_name}. Waiting {fwe.seconds} seconds..."
            await asyncio.sleep(fwe.seconds + 5) # Wait a bit longer
            yield f"  ! Skipping further downloads for {entity_display_name} in this run due to rate limit."
            error_count += 1
        except (ValueError, TypeError) as e_resolve: # Catch potential errors during entity resolution
            yield f"  ! Error processing entity {entity_display_name}: {e_resolve}"
            yield "    (Could be a channel you haven't joined, a deleted account, or other access issue)"
            error_count += 1
        except Exception as e:
            entity_id_str = getattr(entity, 'id', 'N/A')
            yield f"  ! An unexpected error occurred downloading messages for {entity_display_name} (ID: {entity_id_str}): {e}"
            error_count += 1
            # import traceback
            # traceback.print_exc() # For debugging

    yield f"\n--- Download Complete for Folder '{folder_title}' ---"
    yield f"Successfully downloaded message histories for {download_count} chats/users."
    if error_count > 0:
        yield f"Encountered errors for {error_count} chats/users."
    yield f"Files saved in: {folder_output_dir}"

# --- Gradio Interface Definition ---

# Load initial config
initial_config = load_config()

with gr.Blocks() as demo:
    gr.Markdown("# Telegram Chat Exporter")

    # State variables
    client_state = gr.State(None)
    sent_code_state = gr.State(None)
    auth_status_state = gr.State("NotConnected") # "NotConnected", "NeedCode", "NeedPassword", "Authorized", "Error"
    fetched_filters_state = gr.State({})
    folder_list_state = gr.State([]) # Store the list for the dropdown

    with gr.Tabs():
        with gr.TabItem("1. Connection"):
            with gr.Row():
                api_id_input = gr.Textbox(label="API ID", value=initial_config.get('api_id', ''), type="text")
                api_hash_input = gr.Textbox(label="API Hash", value=initial_config.get('api_hash', ''), type="password")
            phone_number_input = gr.Textbox(label="Phone Number (+1234567890)", value=initial_config.get('phone_number', ''), type="text")
            connect_button = gr.Button("Connect / Authenticate", variant="primary")

            with gr.Group(visible=False) as code_group:
                 gr.Markdown("Enter the code sent to your Telegram account.")
                 code_input = gr.Textbox(label="Verification Code", type="text")
                 submit_code_button = gr.Button("Submit Code")

            with gr.Group(visible=False) as password_group:
                 gr.Markdown("Enter your Telegram 2FA Password.")
                 password_input = gr.Textbox(label="Password", type="password")
                 submit_password_button = gr.Button("Submit Password")

        with gr.TabItem("2. Select Folder & Download"):
            with gr.Row():
                fetch_folders_button = gr.Button("Fetch Folders")
                folder_dropdown = gr.Dropdown(label="Select Folder", choices=[], interactive=True)
            with gr.Row():
                 message_limit_input = gr.Textbox(label="Message Limit per Chat (leave blank for all)", value="100", type="text") # Default to 100
            with gr.Row():
                 export_peers_button = gr.Button("Export Users/Chats in Folder (CSV)")
                 #download_button = gr.Button("Download Messages for Folder", variant="primary")
            # Add an invisible file component for download triggering
            file_output = gr.File(label="Download CSV", visible=False)


    output_log = gr.Textbox(label="Log Output", lines=15, interactive=False, autoscroll=True)

    # --- Event Handlers ---

    async def handle_connect(api_id, api_hash, phone):
        """Handles the connect button click."""
        status_updates = []
        new_client = None
        new_sent_code = None
        auth_status = "Error" # Default status

        # Collect all yielded items
        async for status in connect_and_authenticate(api_id, api_hash, phone):
            status_updates.append(status)

        # Process yields: last tuple is state, others are logs
        final_state_tuple = None
        log_output_list = []
        for status in status_updates:
            if isinstance(status, tuple) and len(status) == 4:
                 final_state_tuple = status # Keep track of the latest state tuple
            elif isinstance(status, str):
                 log_output_list.append(status) # Collect log messages
            # Ignore other types if any

        # Unpack the final state tuple if found
        if final_state_tuple:
            new_client, new_sent_code, _, auth_status = final_state_tuple
        else: # Handle cases where the generator might exit unexpectedly
             log_output_list.append("Error: Authentication process did not yield final state.")
             # Ensure client state reflects potential failure
             new_client = None
             new_sent_code = None
             auth_status = "Error"


        log_output = "\n".join(log_output_list)

        # Update UI visibility based on auth_status
        show_code = auth_status == "NeedCode"
        show_password = auth_status == "NeedPassword"

        return {
            client_state: new_client,
            sent_code_state: new_sent_code,
            auth_status_state: auth_status,
            output_log: log_output,
            code_group: gr.update(visible=show_code),
            password_group: gr.update(visible=show_password),
            connect_button: gr.update(interactive=not (show_code or show_password)), # Disable connect btn when waiting
            api_id_input: gr.update(interactive=not (show_code or show_password)),
            api_hash_input: gr.update(interactive=not (show_code or show_password)),
            phone_number_input: gr.update(interactive=not (show_code or show_password)),
        }

    connect_button.click(
        handle_connect,
        inputs=[api_id_input, api_hash_input, phone_number_input],
        outputs=[client_state, sent_code_state, auth_status_state, output_log, code_group, password_group,
                 connect_button, api_id_input, api_hash_input, phone_number_input] # Add button/inputs to outputs
    )

    async def handle_submit_code(current_client, current_sent_code, phone, code):
        """Handles the submit code button click."""
        status_updates = []
        new_client = current_client # Start with current client
        auth_status = "Error" # Default status

        async for status in submit_telegram_code(current_client, current_sent_code, phone, code):
             status_updates.append(status)

        final_state_tuple = None
        log_output_list = []
        for status in status_updates:
            if isinstance(status, tuple) and len(status) == 3:
                 final_state_tuple = status
            elif isinstance(status, str):
                 log_output_list.append(str(status))

        if final_state_tuple:
             # Unpack state, note the middle element (sent_code_info) is ignored here, use current_sent_code below
             new_client, _, auth_status = final_state_tuple
        else:
             log_output_list.append("Error: Code submission process did not yield final state.")
             # Keep client as is? Or nullify? Let's assume it might still be valid if Error/NeedCode
             auth_status = "Error" # Or maybe NeedCode? Depends on where error occurred. Let's default to Error.


        log_output = "\n".join(log_output_list)

        show_code = auth_status == "NeedCode"
        show_password = auth_status == "NeedPassword"

        # Enable connection fields only if authorized or back to square one (error state might require reconnect)
        enable_connect_fields = auth_status == "Authorized" or auth_status == "Error"

        return {
             client_state: new_client,
             # Keep sent_code_info if we're still in NeedCode, otherwise clear it
             sent_code_state: current_sent_code if auth_status == "NeedCode" else None,
             auth_status_state: auth_status,
             output_log: log_output,
             code_group: gr.update(visible=show_code),
             password_group: gr.update(visible=show_password),
             code_input: "" ,# Clear code input
             # Update connect button interactivity
             connect_button: gr.update(interactive=enable_connect_fields),
             api_id_input: gr.update(interactive=enable_connect_fields),
             api_hash_input: gr.update(interactive=enable_connect_fields),
             phone_number_input: gr.update(interactive=enable_connect_fields),
        }

    submit_code_button.click(
         handle_submit_code,
         inputs=[client_state, sent_code_state, phone_number_input, code_input],
         outputs=[client_state, sent_code_state, auth_status_state, output_log, code_group, password_group, code_input,
                  connect_button, api_id_input, api_hash_input, phone_number_input] # Add connect fields to outputs
    )


    async def handle_submit_password(current_client, password):
        """Handles the submit password button click."""
        status_updates = []
        new_client = current_client
        auth_status = "Error"

        async for status in submit_telegram_password(current_client, password):
             status_updates.append(status)

        final_state_tuple = None
        log_output_list = []
        for status in status_updates:
            if isinstance(status, tuple) and len(status) == 2:
                 final_state_tuple = status
            elif isinstance(status, str):
                 log_output_list.append(str(status))

        if final_state_tuple:
            new_client, auth_status = final_state_tuple
        else:
            log_output_list.append("Error: Password submission process did not yield final state.")
            auth_status = "Error"


        log_output = "\n".join(log_output_list)

        show_password = auth_status == "NeedPassword"
        # Enable connection fields only if authorized or error requires reconnect
        enable_connect_fields = auth_status == "Authorized" or auth_status == "Error"

        return {
             client_state: new_client,
             auth_status_state: auth_status,
             output_log: log_output,
             password_group: gr.update(visible=show_password),
             password_input: "", # Clear password input
             # Update connect button interactivity
             connect_button: gr.update(interactive=enable_connect_fields),
             api_id_input: gr.update(interactive=enable_connect_fields),
             api_hash_input: gr.update(interactive=enable_connect_fields),
             phone_number_input: gr.update(interactive=enable_connect_fields),
        }

    submit_password_button.click(
        handle_submit_password,
        inputs=[client_state, password_input],
        outputs=[client_state, auth_status_state, output_log, password_group, password_input,
                 connect_button, api_id_input, api_hash_input, phone_number_input] # Add connect fields to outputs
    )


    async def handle_fetch_folders(current_client, current_auth_status):
        """Handles the fetch folders button click."""
        if current_auth_status != "Authorized":
             # Return directly as this isn't an async generator call issue
             return {
                 output_log: "Please connect and authorize first.",
                 folder_dropdown: gr.update(choices=[], value=None), # Clear dropdown
                 fetched_filters_state: {}, # Clear filters state
                 folder_list_state: [], # Clear folder list state
             }

        status_updates = []
        folders = []
        new_fetched_filters = {}
        status_msg = "Error" # Default

        async for status in get_folders(current_client):
             status_updates.append(status)

        final_state_tuple = None
        log_output_list = []
        for status in status_updates:
             if isinstance(status, tuple) and len(status) == 3:
                 final_state_tuple = status
             elif isinstance(status, str):
                 log_output_list.append(str(status))

        if final_state_tuple:
             folders, new_fetched_filters, status_msg = final_state_tuple
             # Add the status message to the log if it wasn't already yielded as a string
             if status_msg not in log_output_list and status_msg != "Folders fetched.": # Avoid redundant success message if already logged
                 log_output_list.append(status_msg)
        else:
             log_output_list.append("Error: Folder fetching process did not yield final state.")
             # Ensure states are cleared on error
             folders = []
             new_fetched_filters = {}


        log_output = "\n".join(log_output_list)

        # Ensure folders is a list of tuples/lists suitable for Dropdown
        valid_folders = [f for f in folders if isinstance(f, (tuple, list)) and len(f) >= 2] # Check length >= 2

        return {
             output_log: log_output,
             fetched_filters_state: new_fetched_filters,
             folder_list_state: valid_folders, # Store the valid list
             folder_dropdown: gr.update(choices=valid_folders, value=valid_folders[0][1] if valid_folders else None, interactive=True) # Update choices and select first if available
        }


    fetch_folders_button.click(
        handle_fetch_folders,
        inputs=[client_state, auth_status_state],
        outputs=[output_log, fetched_filters_state, folder_list_state, folder_dropdown]
    )

    async def handle_export_peers(current_client, auth_status, folder_id, folder_list, current_filters):
        """Handles the export peers button click. Yields logs and the final CSV file path."""
        # Clear previous file output first
        yield {output_log: "Starting export...", file_output: None}

        if auth_status != "Authorized":
             yield {output_log: "Please connect and authorize first."}
             return
        if not folder_id:
             yield {output_log: "Please fetch and select a folder first."}
             return

        # Find the display title from the folder_list state
        folder_title = "Selected Folder" # Default
        selected_folder_info = None
        for display, f_id in folder_list:
            if str(f_id) == str(folder_id):
                 selected_folder_info = (display, f_id)
                 # Extract title before the " (ID: ...)" part more robustly
                 match = re.match(r"^(.*?)\s*\(ID:\s*\d+\)$", display)
                 folder_title = match.group(1).strip() if match else display # Fallback if format doesn't match
                 break

        if not selected_folder_info:
            yield {output_log: f"Could not find details for selected folder ID: {folder_id}"}
            return


        # Use the core export logic function
        # This function will yield status strings and potentially the file path at the end
        status_updates = []
        final_csv_path = None
        try:
            async for status_or_path in export_folder_peers(current_client, folder_id, folder_title, current_filters):
                if isinstance(status_or_path, str) and os.path.exists(status_or_path) and status_or_path.endswith('.csv'):
                    # Assume this is the file path yield
                    final_csv_path = status_or_path
                    status_updates.append(f"CSV generated: {os.path.basename(final_csv_path)}") # Add short msg to log
                    # Don't yield the path to the log, yield it to the file component below
                elif isinstance(status_or_path, str):
                    status_updates.append(status_or_path)
                    yield {output_log: "\n".join(status_updates)} # Update log progressively
                else:
                    # Handle unexpected yield type if necessary
                     status_updates.append(f"Unexpected status type: {type(status_or_path)}")
                     yield {output_log: "\n".join(status_updates)}


        except Exception as e:
            status_updates.append(f"An unexpected error occurred during export: {e}")
            # Potentially log traceback here for debugging
            yield {output_log: "\n".join(status_updates)}
            # Ensure no file path is returned on error
            final_csv_path = None

        # Final update after loop finishes
        if final_csv_path:
             yield {output_log: "\n".join(status_updates), file_output: gr.update(value=final_csv_path, visible=True)} # Yield path to file output
        else:
             # Ensure log shows completion or error state without providing a file
             if "error" not in status_updates[-1].lower() and "failed" not in status_updates[-1].lower():
                 status_updates.append("Export finished, but no CSV file was generated (e.g., no peers found or error saving).")
             yield {output_log: "\n".join(status_updates), file_output: None}


    # Modify the core export function slightly to yield the path as the *last* item on success
    async def export_folder_peers(current_client, folder_id, folder_title, current_fetched_filters):
        """Exports peers, yields status strings, and finally yields the CSV file path on success."""
        if not current_client or not folder_id or not current_fetched_filters:
            yield "Client not ready, folder not selected, or filter data missing."
            return

        selected_filter_object = current_fetched_filters.get(int(folder_id))
        csv_filename = None # Initialize

        if selected_filter_object and hasattr(selected_filter_object, 'include_peers') and selected_filter_object.include_peers:
            yield f"Exporting included users/chats for folder '{folder_title}'..."
            sanitized_title = sanitize_filename(folder_title)
            # Ensure BASE_OUTPUT_DIR exists
            os.makedirs(BASE_OUTPUT_DIR, exist_ok=True)
            # Place CSV inside the base output dir
            csv_filename = os.path.join(BASE_OUTPUT_DIR, f"folder_{sanitized_title}_users_chats_{int(time.time())}.csv") # Add timestamp to avoid clashes


            peers_exported_count = 0
            try:
                with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
                    writer = csv.writer(csvfile)
                    writer.writerow(['Type', 'ID', 'Username', 'Display Name', 'Full Name', 'Phone'])

                    peer_tasks = []
                    for peer_input in selected_filter_object.include_peers:
                         peer_tasks.append(process_peer_for_export(current_client, peer_input)) # Refactor processing logic

                    results = await asyncio.gather(*peer_tasks, return_exceptions=True)

                    for result in results:
                        if isinstance(result, Exception):
                            yield f"  - Error processing a peer: {result}" # Log errors from gather
                        elif isinstance(result, dict) and 'error' in result:
                             yield f"  - Warning: {result['error']}" # Log handled warnings/skips
                        elif isinstance(result, list):
                             writer.writerow(result)
                             peers_exported_count += 1
                        # else: ignore None results (e.g. from FloodWait recovery placeholder)


                # After writing is complete
                if peers_exported_count > 0:
                    yield f"Successfully processed details for {peers_exported_count} users/chats."
                    yield f"CSV file ready: {csv_filename}"
                    yield csv_filename # <<< YIELD FILE PATH ON SUCCESS
                else:
                    yield f"No exportable users/chats found or processed successfully in folder '{folder_title}'."
                    # Clean up empty file
                    if csv_filename and os.path.exists(csv_filename):
                        try:
                            if os.path.getsize(csv_filename) <= 100: # Header only or empty
                                os.remove(csv_filename)
                                yield f"Removed empty file: {csv_filename}"
                        except OSError as e_rem:
                            yield f"Warning: Could not remove empty file {csv_filename}: {e_rem}"


            except IOError as e_csv:
                yield f"Error writing CSV file {csv_filename}: {e_csv}"
                # Clean up potentially partially written file on error
                if csv_filename and os.path.exists(csv_filename):
                    try:
                        os.remove(csv_filename)
                        yield f"Removed partially written file due to error: {csv_filename}"
                    except OSError as e_rem:
                         yield f"Warning: Could not remove file {csv_filename} after write error: {e_rem}"

            except Exception as e_main:
                 yield f"An unexpected error occurred during CSV export: {e_main}"
                 # Clean up potentially partially written file on error
                 if csv_filename and os.path.exists(csv_filename):
                     try:
                         os.remove(csv_filename)
                         yield f"Removed partially written file due to error: {csv_filename}"
                     except OSError as e_rem:
                          yield f"Warning: Could not remove file {csv_filename} after error: {e_rem}"


        elif selected_filter_object:
             yield f"Folder '{folder_title}' does not seem to contain specific included peers to export."
        else:
             yield f"Could not find filter details for folder ID {folder_id}."
        # No file path yielded if we reach here without success


    # Helper for asyncio.gather in export_folder_peers
    async def process_peer_for_export(current_client, peer_input):
        """Gets entity details for a single peer, handles errors."""
        try:
            input_peer = await current_client.get_input_entity(peer_input)
            entity = await current_client.get_entity(input_peer)

            entity_type = type(entity).__name__
            username = getattr(entity, 'username', '') or ''
            display_name = getattr(entity, 'title', None) or getattr(entity, 'username', None) or getattr(entity, 'first_name', f"ID: {entity.id}")
            if not display_name and hasattr(entity, 'first_name'):
                 display_name = entity.first_name + (f" {entity.last_name}" if getattr(entity, 'last_name', None) else "")

            full_name = (getattr(entity, 'first_name', '') or '') + ' ' + (getattr(entity, 'last_name', '') or '')
            full_name = full_name.strip()
            phone = getattr(entity, 'phone', '') or ''

            return [ # Return data as list for CSV row
                entity_type,
                entity.id,
                username,
                display_name,
                full_name if full_name else display_name,
                phone
            ]
        except ValueError:
             return {'error': f"Could not resolve peer: {peer_input}. Might be inaccessible."}
        except FloodWaitError as fwe_peer:
             # Logged by the handler, maybe just return None or a placeholder?
             # Yielding from here is complex with gather. Return error dict.
             await asyncio.sleep(fwe_peer.seconds + 1) # Wait here as we can't yield easily
             return {'error': f"Rate limit hit for peer {peer_input}. Waited {fwe_peer.seconds}s. Skipped in this batch."}
             # Or retry logic could be added here, but makes it more complex
        except Exception as e_peer:
             return {'error': f"Error processing peer {peer_input}: {e_peer}"}


    export_peers_button.click(
        handle_export_peers,
        inputs=[client_state, auth_status_state, folder_dropdown, folder_list_state, fetched_filters_state],
        outputs=[output_log, file_output] # Send logs to log, file path to file component
    )


    async def handle_download(current_client, auth_status, folder_id, folder_list, current_filters, limit):
        """Handles the download button click."""
        # Keep track of log messages
        log_updates = []
        def update_log(msg):
            log_updates.append(msg)
            return "\n".join(log_updates) # Return cumulative log

        yield update_log("Starting download process...") # Initial message

        if auth_status != "Authorized":
             yield update_log("Please connect and authorize first.")
             return
        if not folder_id:
             yield update_log("Please fetch and select a folder first.")
             return

        # Find the display title from the folder_list state
        folder_title = "Selected Folder" # Default
        selected_folder_info = None
        for display, f_id in folder_list:
            if str(f_id) == str(folder_id):
                selected_folder_info = (display, f_id)
                match = re.match(r"^(.*?)\s*\(ID:\s*\d+\)$", display)
                folder_title = match.group(1).strip() if match else display
                break

        if not selected_folder_info:
            yield update_log(f"Could not find details for selected folder ID: {folder_id}")
            return

        # Use the core download logic function which yields status updates
        try:
            async for status in download_messages_for_folder(current_client, folder_id, folder_title, current_filters, limit):
                 yield update_log(status) # Yield cumulative log as generator progresses
        except Exception as e:
             yield update_log(f"An unexpected error occurred during download initiation or iteration: {e}")
             # Add traceback logging here if needed for debugging server-side


    #download_button.click(
    #    handle_download,
    #    inputs=[client_state, auth_status_state, folder_dropdown, folder_list_state, fetched_filters_state, message_limit_input],
    #    outputs=[output_log] # Only output logs for this button
    #)


# --- Main Execution ---
if __name__ == '__main__':
    # Remove the old asyncio.run(main()) block
    # Make sure BASE_OUTPUT_DIR exists
    os.makedirs(BASE_OUTPUT_DIR, exist_ok=True)
    print(f"Base output directory: {os.path.abspath(BASE_OUTPUT_DIR)}")
    print("Launching Gradio interface...")
    # Use share=True if you need to access it from other devices on your network
    demo.launch(share=True)
    print("Gradio interface closed.")