File size: 35,455 Bytes
41a6f7c
0edd3ba
41a6f7c
0edd3ba
 
2752102
41a6f7c
0edd3ba
 
 
41a6f7c
8a3568a
0edd3ba
8a3568a
0edd3ba
 
8a3568a
e6483ce
0edd3ba
e6483ce
 
 
 
 
 
 
 
 
 
0edd3ba
9f613f2
 
 
0edd3ba
9f613f2
 
 
 
 
 
 
 
 
 
0edd3ba
9f613f2
0edd3ba
 
 
 
2752102
 
 
 
 
 
 
 
9f613f2
0edd3ba
9f613f2
0edd3ba
2752102
9f613f2
 
0edd3ba
9f613f2
2752102
0edd3ba
9f613f2
2752102
0edd3ba
9f613f2
 
 
 
 
0edd3ba
2752102
0edd3ba
 
9f613f2
 
0edd3ba
9f613f2
0edd3ba
 
dc11f97
 
0edd3ba
dc11f97
0edd3ba
 
 
dc11f97
 
faa1e36
 
 
 
2752102
faa1e36
2752102
 
faa1e36
2752102
faa1e36
dc11f97
faa1e36
 
 
 
 
 
2752102
faa1e36
 
 
 
 
 
2752102
faa1e36
 
0edd3ba
faa1e36
 
 
0edd3ba
 
faa1e36
 
 
 
 
2752102
 
faa1e36
 
 
 
 
 
 
 
 
 
 
 
 
2752102
faa1e36
0edd3ba
 
2752102
9f613f2
0edd3ba
9f613f2
 
0edd3ba
 
2752102
9f613f2
0edd3ba
9f613f2
2f6a202
0edd3ba
 
 
 
2752102
2f6a202
0edd3ba
2752102
0edd3ba
 
2752102
9f613f2
0edd3ba
9f613f2
 
0edd3ba
 
 
2752102
9f613f2
0edd3ba
9f613f2
 
0edd3ba
 
 
2752102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f613f2
0edd3ba
9f613f2
 
0edd3ba
 
 
2752102
0edd3ba
 
9f613f2
 
0edd3ba
 
 
2752102
9f613f2
0edd3ba
9f613f2
 
0edd3ba
 
2752102
9f613f2
0edd3ba
9f613f2
 
0edd3ba
 
2752102
9f613f2
0edd3ba
9f613f2
 
dc11f97
0edd3ba
 
 
 
2752102
9f613f2
0edd3ba
9f613f2
 
0edd3ba
 
2752102
9f613f2
0edd3ba
9f613f2
 
dc11f97
0edd3ba
 
 
 
2752102
9f613f2
0edd3ba
9f613f2
 
 
 
0edd3ba
 
 
 
2752102
9f613f2
0edd3ba
9f613f2
 
 
0edd3ba
 
2752102
0edd3ba
 
9f613f2
 
 
0edd3ba
 
2752102
9f613f2
0edd3ba
9f613f2
0edd3ba
 
 
 
 
2752102
9f613f2
0edd3ba
9f613f2
 
dc11f97
0edd3ba
 
 
 
2752102
9f613f2
0edd3ba
 
9f613f2
0edd3ba
 
2752102
9f613f2
0edd3ba
 
9f613f2
dc11f97
0edd3ba
 
 
 
2752102
9f613f2
0edd3ba
9f613f2
2752102
dc11f97
0edd3ba
 
 
 
2752102
483d941
0edd3ba
483d941
 
0edd3ba
 
dc11f97
0edd3ba
 
 
 
 
 
 
483d941
0edd3ba
 
 
2752102
41a6f7c
0edd3ba
dc11f97
0edd3ba
 
 
 
2752102
8a3568a
0edd3ba
8a3568a
 
0edd3ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc11f97
2752102
6f91c0b
0edd3ba
 
 
 
 
 
2752102
0edd3ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2752102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0edd3ba
2752102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0edd3ba
ca1d775
0edd3ba
9f613f2
2752102
1add323
0edd3ba
 
2752102
0edd3ba
ca1d775
abf04cf
20dc0d7
0edd3ba
bbda96c
abf04cf
 
2752102
 
 
 
 
 
 
 
 
 
 
 
abf04cf
0edd3ba
abf04cf
0edd3ba
dc11f97
2752102
0edd3ba
2752102
 
dc11f97
faa1e36
2752102
faa1e36
 
2752102
faa1e36
 
 
 
 
 
 
2752102
faa1e36
 
 
 
2752102
faa1e36
0edd3ba
 
2752102
 
 
 
0edd3ba
 
 
 
 
 
 
 
abf04cf
0edd3ba
 
 
2752102
 
 
 
dc11f97
faa1e36
 
2752102
faa1e36
2752102
faa1e36
2752102
faa1e36
 
2752102
faa1e36
 
 
 
 
 
0edd3ba
2752102
6fe2453
faa1e36
2752102
 
 
faa1e36
 
 
 
2752102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faa1e36
6fb9093
 
2752102
6fb9093
0edd3ba
6fb9093
d0437d1
bbda96c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
def get_file_content(owner, repo_name, path, branch="main"):
    """Fetches file content from a GitHub repository."""
    url = f"https://raw.githubusercontent.com/{owner}/{repo_name}/{branch}/{path}"
    try:
        response = requests.get(url)
        response.raise_for_status()
        return response.text
    except requests.exceptions.RequestException as e:
        return f"Error fetching file: {e}"


def extract_repo_info(url):
    """Extracts owner and repo name from a GitHub URL."""
    match = re.search(r"github\.com/([^/]+)/([^/]+)", url)
    return match.group(1), match.group(2) if match else (None, None)


def analyze_file_content(content, file_path):
    """Analyzes file content and returns statistics."""
    lines = content.splitlines()
    word_count = sum(len(line.split()) for line in lines)
    line_count = len(lines)
    file_extension = file_path.split('.')[-1].lower() if '.' in file_path else "unknown"
    return {
        "line_count": line_count,
        "word_count": word_count,
        "file_extension": file_extension,
    }


def github_tool(
    action: str,
    repo_name: str = None,
    branch: str = "main",
    path: str = None,
    content: str = None,
    message: str = None,
    owner: str = None,
    vcs_url: str = None,
    title: str = None,
    body: str = None,
    base: str = None,
    head: str = None,
    issue_number: int = None,
    labels: str = None,
    tag: str = None,
    name: str = None,
    file_url: str = None,
    repo_url: str = None,
    template_name: str = None,
    template_params: dict = None,
    diff: str = None,
    diff_message: str = None,
    new_description: str = None,
    issue_title: str = None,
    issue_body: str = None,
    issue_state: str = None,
    **kwargs
):
    """Manages GitHub repositories."""
    user = g.get_user()

    try:
        if action == "import_repository":
            if not all([owner, repo_name, vcs_url]):
                raise ValueError("Missing parameters: owner, repo_name, vcs_url")
            try:
                user.get_repo(repo_name)
                return "Repository already exists."
            except GithubException:
                pass

            headers = {
                'Authorization': f'token {GITHUB_TOKEN}',
                'Accept': 'application/vnd.github.v3+json',
            }
            import_url = f'https://api.github.com/repos/{owner}/{repo_name}/import'
            response = requests.put(import_url, json={'vcs_url': vcs_url, 'vcs': 'git'}, headers=headers)
            response.raise_for_status()
            return "Repository import started."

        elif action == "create_repository":
            if not repo_name:
                raise ValueError("Missing parameter: repo_name")
            repo = user.create_repo(name=repo_name)
            return f"Repository **{repo_name}** created! [Open repository]({repo.html_url})"

        elif action == "create_project_from_template":
            if not all([repo_name, template_name]):
                raise ValueError("Missing parameters: repo_name, template_name")
            if template_name not in PROJECT_TEMPLATES:
                raise ValueError(
                    f"Unknown template: {template_name}.  Available: {', '.join(PROJECT_TEMPLATES.keys())}"
                )
            repo = user.create_repo(name=repo_name)
            template = PROJECT_TEMPLATES[template_name]

            template_params_final = {}
            if "params" in template:
                for param_name, param_config in template["params"].items():
                    template_params_final[param_name] = template_params.get(param_name, param_config.get("default")) if template_params else param_config.get("default")

            repo_name_snake_case = repo_name.replace("-", "_")
            readme_filename = "README.md"

            env = jinja2.Environment()

            for file_path, file_content in template["files"].items():
                final_file_path = file_path
                final_file_content = file_content

                if "rename_files" in template:
                    for old_name, new_name_template in template["rename_files"].items():
                        if file_path == old_name:
                            final_file_path = new_name_template.replace("{{repo_name_snake_case}}", repo_name_snake_case).replace("{{repo_name}}", repo_name).replace("{{readme_filename}}", readme_filename)

                template_render = env.from_string(final_file_content)
                final_file_content = template_render.render(
                    repo_name=repo_name,
                    repo_name_snake_case=repo_name_snake_case,
                    readme_filename=readme_filename,
                    **template_params_final
                )

                repo.create_file(
                    final_file_path,
                    f"Create {final_file_path} from template {template_name}",
                    final_file_content,
                    branch="main",
                )

            if "post_process" in template:
                post_process_action = template["post_process"]
                if post_process_action == "install_dependencies":
                    print(
                        f"Post-processing: install_dependencies for {repo_name} (Not fully implemented in this example).")
                elif post_process_action == "shadcn_setup":
                    instructions = f"""
**Konfiguracja Shadcn UI wymaga dodatkowych kroków po stronie klienta!**

1.  **Sklonuj repozytorium:** `git clone https://github.com/{user.login}/{repo_name}.git`
2.  **Przejdź do katalogu projektu:** `cd {repo_name}`
3.  **Zainstaluj zależności:** `npm install` (lub `yarn install`, `pnpm install`)
4.  **Zainicjuj Shadcn UI:** `npx shadcn-ui@latest init`
5.  **Uruchom aplikację:** `npm run dev` (lub odpowiednia komenda dla Twojego menedżera pakietów)

Po wykonaniu tych kroków, Twoja aplikacja Shadcn UI będzie w pełni skonfigurowana i gotowa do rozwoju.
                    """
                    return f"Repository **{repo_name}** created from template **{template_name}**! [Open repository]({repo.html_url})\n\n{instructions}"
                else:
                    print(f"Unknown post-process action: {post_process_action}")

            return f"Repository **{repo_name}** created from template **{template_name}**! [Open repository]({repo.html_url})"

        elif action == "create_file":
            if not all([repo_name, path, content, message]):
                raise ValueError("Missing parameters: repo_name, path, content, message")
            repo = user.get_repo(repo_name)
            repo.create_file(path, message, content, branch=branch)
            return f"File **`{path}`** created in repository **`{repo_name}`** on branch **`{branch}`**."

        elif action == "get_file":
            if not all([repo_name, path]):
                raise ValueError("Missing parameters: repo_name, path")
            repo = user.get_repo(repo_name)
            file_content = repo.get_contents(path, ref=branch)
            return (
                f"File content of **`{path}`** from **`{repo_name}`**:\n\n`\n{file_content.decoded_content.decode()}\n`"
            )

        elif action == "get_file_content_by_url":
            if not file_url:
                raise ValueError("Missing parameter: file_url")
            file_content = get_file_content(None, None, None, None)
            return f"File content from URL **`{file_url}`**:\n\n`\n{file_content}\n`"

        elif action == "delete_file":
            if not all([repo_name, path]):
                raise ValueError("Missing parameters: repo_name, path")
            repo = user.get_repo(repo_name)
            file_contents = repo.get_contents(path, ref=branch)
            repo.delete_file(path, "Delete file", file_contents.sha, branch=branch)
            return f"File **`{path}`** deleted from repository **`{repo_name}`** on branch **`{branch}`**."

        elif action == "update_file":
            if not all([repo_name, path, content, message]):
                raise ValueError("Missing parameters: repo_name, path, content, message")
            repo = user.get_repo(repo_name)
            file_contents = repo.get_contents(path, ref=branch)
            repo.update_file(path, message, content, file_contents.sha, branch=branch)
            return f"File **`{path}`** updated in repository **`{repo_name}`** on branch **`{branch}`**."

        elif action == "update_file_diff":
            if not all([repo_name, path, diff, diff_message]):
                raise ValueError("Missing parameters: repo_name, path, diff, diff_message")
            repo = user.get_repo(repo_name)
            file_contents = repo.get_contents(path, ref=branch)
            current_content_text = file_contents.decoded_content.decode()

            dmp = diff_match_patch()

            try:
                patches = dmp.patch_fromText(diff)
            except ValueError:
                raise ValueError("Invalid patch format. Please provide a valid patch in 'diff' format.")

            patched_content_tuple = dmp.patch_apply(patches, current_content_text)
            patched_content_text = patched_content_tuple[0]
            patch_results = patched_content_tuple[1]

            if not any(patch_results):
                raise ValueError("Failed to apply patch. Diff might be outdated or invalid.")

            repo.update_file(path, diff_message, patched_content_text, file_contents.sha, branch=branch)
            return f"File **`{path}`** updated using diff in repository **`{repo_name}`** on branch **`{branch}`**."


        elif action == "list_branches":
            if not repo_name:
                raise ValueError("Missing parameter: repo_name")
            repo = user.get_repo(repo_name)
            branches = repo.get_branches()
            branch_list = "\n".join([f"- `{branch.name}`" for branch in branches])
            return f"Branches in repository **`{repo_name}`**:\n{branch_list}"

        elif action == "create_branch":
            if not all([repo_name, base, head]):
                raise ValueError("Missing parameters: repo_name, base, head")
            repo = user.get_repo(repo_name)
            source_branch = repo.get_branch(base)
            repo.create_git_ref(ref=f"refs/heads/{head}", sha=source_branch.commit.sha)
            return f"Branch **`{head}`** created from **`{base}`** in repository **`{repo_name}`**."

        elif action == "delete_branch":
            if not all([repo_name, branch]):
                raise ValueError("Missing parameters: repo_name, branch")
            repo = user.get_repo(repo_name)
            repo.get_git_ref(f"heads/{branch}").delete()
            return f"Branch **`{branch}`** deleted from repository **`{repo_name}`**."

        elif action == "create_pull_request":
            if not all([repo_name, title, body, base, head]):
                raise ValueError("Missing parameters: repo_name, title, body, base, head")
            repo = user.get_repo(repo_name)
            pr = repo.create_pull(title=title, body=body, base=base, head=head)
            return f"Pull request created! [Open Pull Request]({pr.html_url})"

        elif action == "list_open_pull_requests":
            if not repo_name:
                raise ValueError("Missing parameter: repo_name")
            repo = user.get_repo(repo_name)
            open_prs = repo.get_pulls(state='open')
            if not open_prs:
                return f"No open pull requests in repository **`{repo_name}`**."
            prs_list = "\n".join([f"- [{pr.title}]({pr.html_url})" for pr in open_prs])
            return f"Open pull requests in repository **`{repo_name}`**:\n{prs_list}"

        elif action == "create_issue":
            if not all([repo_name, title, body]):
                raise ValueError("Missing parameters: repo_name, title, body")
            repo = user.get_repo(repo_name)
            issue = repo.create_issue(title=title, body=body)
            return f"Issue created! [Open Issue]({issue.html_url})"

        elif action == "list_issues":
            if not repo_name:
                raise ValueError("Missing parameter: repo_name")
            repo = user.get_repo(repo_name)
            issues = repo.get_issues(state='open')
            if not issues:
                return f"No open issues in repository **`{repo_name}`**."
            issues_list = "\n".join([f"- [{issue.title}]({issue.html_url})" for issue in issues])
            return f"Open issues in repository **`{repo_name}`**:\n{issues_list}"

        elif action == "add_label_to_issue":
            if not all([repo_name, issue_number, labels]):
                raise ValueError("Missing parameters: repo_name, issue_number, labels")
            repo = user.get_repo(repo_name)
            issue = repo.get_issue(number=int(issue_number))
            for label in labels.split(","):
                issue.add_to_labels(label.strip())
            return (
                f"Labels **`{labels}`** added to issue **#{issue_number}** in repository **`{repo_name}`**."
            )

        elif action == "close_issue":
            if not all([repo_name, issue_number]):
                raise ValueError("Missing parameters: repo_name, issue_number")
            repo = user.get_repo(repo_name)
            issue = repo.get_issue(number=int(issue_number))
            issue.edit(state='closed')
            return f"Issue **#{issue_number}** closed in repository **`{repo_name}`**."

        elif action == "add_comment_to_issue":
            if not all([repo_name, issue_number, message]):
                raise ValueError("Missing parameters: repo_name, issue_number, message")
            repo = user.get_repo(repo_name)
            issue = repo.get_issue(number=int(issue_number))
            issue.create_comment(body=message)
            return f"Comment added to issue **#{issue_number}** in repository **`{repo_name}`**."

        elif action == "create_release":
            if not all([repo_name, tag, name, message]):
                raise ValueError("Missing parameters: repo_name, tag, name, message")
            repo = user.get_repo(repo_name)
            release = repo.create_git_release(tag=tag, name=name, message=message)
            return (
                f"Release **`{name}`** created in repository **`{repo_name}`**! [Open Release]({release.html_url})"
            )

        elif action == "list_releases":
            if not repo_name:
                raise ValueError("Missing parameter: repo_name")
            repo = user.get_repo(repo_name)
            releases = repo.get_releases()
            if not releases:
                return f"No releases in repository **`{repo_name}`**."
            releases_list = "\n".join([f"- [{release.tag_name}]({release.html_url})" for release in releases])
            return f"Releases in repository **`{repo_name}`**:\n{releases_list}"

        elif action == "fork_repository":
            if not repo_name:
                raise ValueError("Missing parameter: repo_name")
            repo = g.get_repo(repo_name)
            fork = user.create_fork(repo)
            return f"Repository **`{repo_name}`** forked! [Open fork]({fork.html_url})"

        elif action == "list_forks":
            if not repo_name:
                raise ValueError("Missing parameter: repo_name")
            repo = g.get_repo(repo_name)
            forks = repo.get_forks()
            if not forks:
                return f"No forks of repository **`{repo_name}`**."
            forks_list = "\n".join([f"- [{fork.full_name}]({fork.html_url})" for fork in forks])
            return f"Forks of repository **`{repo_name}`**:\n{forks_list}"

        elif action == "list_files":
            if not all([owner, repo_name]):
                raise ValueError("Missing parameters: owner, repo_name")
            repo = g.get_repo(f"{owner}/{repo_name}")
            contents = repo.get_contents("" if not path else path)
            if not contents:
                return f"No files in path **`{path}`** of repository **`{repo_name}`**."
            files_list = "\n".join([f"- [{content.name}]({content.download_url})" for content in contents])
            return f"Files in path **`{path}`** of repository **`{repo_name}`**:\n{files_list}"

        elif action == "get_repository_info":
            if not all([owner, repo_name]):
                raise ValueError("Missing parameters: owner, repo_name")
            repo = g.get_repo(f"{owner}/{repo_name}")
            info = {
                "Name": repo.name,
                "Description": repo.description,
                "URL": repo.html_url,
                "Owner": repo.owner.login,
                "Default branch": repo.default_branch,
                "Language": repo.language,
                "Stars": repo.stargazers_count,
                "Forks": repo.forks_count,
                "Created at": str(repo.created_at),
                "Last updated": str(repo.updated_at),
            }
            info_md = "\n".join([f"- **{key}**: {value}" for key, value in info.items()])
            return f"Repository info for **`{repo_name}`**:\n{info_md}"

        elif action == "get_file_content":
            if not all([owner, repo_name, path]):
                raise ValueError("Missing parameters: owner, repo_name, path")
            content_text = get_file_content(owner, repo_name, path, branch)
            return (
                f"File content of **`{path}`** from repository **`{repo_name}`**:\n\n`\n{content_text}\n`"
            )

        elif action == "analyze_repository_by_url":
            if not repo_url:
                raise ValueError("Missing parameter: repo_url")
            owner, repo_name = extract_repo_info(repo_url)
            if not owner or not repo_name:
                raise ValueError("Invalid repository URL")

            repo = g.get_repo(f"{owner}/{repo_name}")
            contents = repo.get_contents("")
            file_analyses = []
            for content in contents:
                if content.type == "file":
                    file_content = content.decoded_content.decode()
                    analysis = analyze_file_content(file_content, content.path)
                    file_analyses.append({
                        "name": content.name,
                        "path": content.path,
                        "analysis": analysis,
                    })
            analysis_md = "Repository file analysis:\n" + "\n".join([
                f"- **{f['path']}**:\n"
                f"  - Lines: {f['analysis']['line_count']}\n"
                f"  - Words: {f['analysis']['word_count']}\n"
                f"  - Extension: {f['analysis']['file_extension']}"
                for f in file_analyses
            ])
            return analysis_md

        elif action == "analyze_repository_content":
            if not all([owner, repo_name]):
                raise ValueError("Missing parameters: owner, repo_name")
            repo = g.get_repo(f"{owner}/{repo_name}")
            contents = repo.get_contents("")
            file_analyses = []
            for content in contents:
                if content.type == "file":
                    file_content = get_file_content(owner, repo_name, content.path, branch)
                    analysis = analyze_file_content(file_content, content.path)
                    file_analyses.append({
                        "name": content.name,
                        "path": content.path,
                        "analysis": analysis,
                    })
            analysis_md = "Repository content analysis:\n" + "\n".join([
                f"- **{f['path']}**:\n"
                f"  - Lines: {f['analysis']['line_count']}\n"
                f"  - Words: {f['analysis']['word_count']}\n"
                f"  - Extension: {f['analysis']['file_extension']}"
                for f in file_analyses
            ])
            return analysis_md

        elif action == "delete_repository":
            if not repo_name:
                raise ValueError("Missing parameter: repo_name")
            repo = user.get_repo(repo_name)
            repo.delete()
            return f"Repository **`{repo_name}`** deleted!"

        elif action == "update_repository_description":
            if not all([repo_name, new_description]):
                raise ValueError("Missing parameters: repo_name, new_description")
            repo = user.get_repo(repo_name)
            repo.edit(description=new_description)
            return f"Repository **`{repo_name}`** description updated to: \"{new_description}\""

        elif action == "edit_issue":
            if not all([repo_name, issue_number]):
                raise ValueError("Missing parameters: repo_name, issue_number")
            repo = user.get_repo(repo_name)
            issue = repo.get_issue(number=int(issue_number))
            issue_update_params = {}
            if issue_title is not None:
                issue_update_params['title'] = issue_title
            if issue_body is not None:
                issue_update_params['body'] = issue_body
            if issue_state is not None:
                issue_update_params['state'] = issue_state
            if not issue_update_params:
                raise ValueError("No issue details to update provided (title, body, or state)")
            issue.edit(**issue_update_params)
            updated_fields = ", ".join(issue_update_params.keys())
            return f"Issue **#{issue_number}** in repository **`{repo_name}`** updated fields: {updated_fields}"

        elif action == "list_closed_issues":
            if not repo_name:
                raise ValueError("Missing parameter: repo_name")
            repo = user.get_repo(repo_name)
            issues = repo.get_issues(state='closed')
            if not issues:
                return f"No closed issues in repository **`{repo_name}`**."
            issues_list = "\n".join([f"- [{issue.title}]({issue.html_url})" for issue in issues])
            return f"Closed issues in repository **`{repo_name}`**:\n{issues_list}"

        elif action == "get_issue_details":
            if not all([repo_name, issue_number]):
                raise ValueError("Missing parameters: repo_name, issue_number")
            repo = user.get_repo(repo_name)
            issue = repo.get_issue(number=int(issue_number))
            comments = issue.get_comments()
            details = f"""
**Issue #{issue.number}: {issue.title}**
State: {issue.state}
Created At: {issue.created_at}
Author: {issue.user.login}

**Body:**
{issue.body}

**Comments:**
"""
            if comments:
                for comment in comments:
                    details += f"""
---
**{comment.user.login}** at {comment.created_at}:
{comment.body}
"""
            else:
                details += "No comments."

            return details

        else:
            raise ValueError(f"Unknown action: {action}")

    except GithubException as e:
        return f"**GitHub Error:** {e}"
    except ValueError as e:
        return f"**Error:** {e}"
    except requests.exceptions.RequestException as e:
        return f"**Connection Error:** {e}"
    except Exception as e:
        return f"**Unexpected Error:** {e}"


with gr.Blocks() as demo:
    gr.Markdown("# GitHub Tool Plugingit (Simplified Interface)")

    with gr.Column():
        action = gr.Dropdown(
            choices=[
                "import_repository", "create_repository", "create_project_from_template",
                "create_file", "get_file", "get_file_content_by_url",
                "delete_file", "update_file", "update_file_diff",
                "list_branches", "create_branch", "delete_branch",
                "create_pull_request", "list_open_pull_requests",
                "create_issue", "list_issues", "list_closed_issues", "get_issue_details",
                "add_label_to_issue", "close_issue", "add_comment_to_issue",
                "create_release", "list_releases",
                "fork_repository", "list_forks",
                "list_files", "get_repository_info",
                "analyze_repository_by_url", "analyze_repository_content",
                "delete_repository", "update_repository_description", "edit_issue"
            ],
            label="Select Action",
        )
        repo_name = gr.Textbox(label="Repository Name")
        template_name = gr.Dropdown(
            choices=[""] + list(PROJECT_TEMPLATES.keys()),
            label="Project Template",
            value="",
            allow_custom_value=True,
        )
        template_params_ui = {}
        with gr.Row():
            for template_key, template_config in PROJECT_TEMPLATES.items():
                if "params" in template_config:
                    with gr.Column(visible=False, elem_classes=f"params_{template_key}") as params_section:
                        for param_name, param_details in template_config["params"].items():
                            if param_details["type"] == "choice":
                                template_params_ui[param_name] = gr.Dropdown(
                                    choices=param_details["choices"],
                                    label=param_details["description"] or param_name,
                                    value=param_details["default"]
                                )
                            else:
                                template_params_ui[param_name] = gr.Textbox(
                                    label=param_details["description"] or param_name,
                                    value=param_details["default"] if "default" in param_details else ""
                                )
                    template_params_ui[template_key] = params_section

        branch = gr.Textbox(label="Branch", value="main")
        path = gr.Textbox(label="File Path")
        content = gr.Code(label="File Content", lines=5, language='python', visible=True)
        diff = gr.Code(label="Diff Content", lines=5, language='diff', visible=False)
        message = gr.Textbox(label="Message/Comment", visible=True)
        diff_message = gr.Textbox(label="Diff Message", visible=False)
        owner = gr.Textbox(label="Owner")
        vcs_url = gr.Textbox(label="VCS URL")
        title = gr.Textbox(label="Title")
        body = gr.Textbox(label="Body")
        base = gr.Textbox(label="Base Branch")
        head = gr.Textbox(label="Head Branch/New Branch")
        issue_number = gr.Number(label="Issue Number", precision=0)
        labels = gr.Textbox(label="Labels (comma-separated)")
        tag = gr.Textbox(label="Tag")
        release_name = gr.Textbox(label="Release Name")
        file_url = gr.Textbox(label="File URL")
        repo_url = gr.Textbox(label="Repository URL")
        new_description = gr.Textbox(label="New Repository Description", visible=False)
        issue_title = gr.Textbox(label="New Issue Title", visible=False)
        issue_body = gr.Textbox(label="New Issue Body", visible=False, lines=3)
        issue_state = gr.Dropdown(label="New Issue State (open/closed)", choices=["open", "closed", None], value=None, allow_none=True, visible=False)

    def show_template_params(template_name):
        visibility_map = {key: gr.Column.update(visible=False) for key in PROJECT_TEMPLATES if
                          "params" in PROJECT_TEMPLATES[key]}
        if template_name and template_name in PROJECT_TEMPLATES and "params" in PROJECT_TEMPLATES[template_name]:
            visibility_map[template_name] = gr.Column.update(visible=True)
        return [visibility_map.get(key, gr.Column.update(visible=False)) for key in PROJECT_TEMPLATES if
                "params" in PROJECT_TEMPLATES[key]]

    template_param_visibility_outputs = [template_params_ui[key] for key in PROJECT_TEMPLATES if
                                         "params" in PROJECT_TEMPLATES[key]]
    template_name.change(
        show_template_params,
        inputs=[template_name],
        outputs=template_param_visibility_outputs
    )

    run_button = gr.Button("Execute")
    output = gr.Markdown(label="Result")

    input_components = [
        action, repo_name, branch, path, content, message, owner, vcs_url, title, body, base, head, issue_number,
        labels, tag, release_name, file_url, repo_url, template_name, new_description, issue_title, issue_body,
        issue_state, diff, diff_message
    ]

    for template_key in PROJECT_TEMPLATES:
        if "params" in PROJECT_TEMPLATES[template_key]:
            for param_name in template_params_ui:
                if param_name in PROJECT_TEMPLATES[template_key]["params"]:
                    input_components.append(template_params_ui[param_name])

    def show_hide_input_fields(action_name):
        visibility_map = {
            "repo_name": gr.Textbox.update(visible=False),
            "branch": gr.Textbox.update(visible=False),
            "path": gr.Textbox.update(visible=False),
            "content": gr.Code.update(visible=False),
            "diff": gr.Code.update(visible=False),
            "message": gr.Textbox.update(visible=False),
            "diff_message": gr.Textbox.update(visible=False),
            "owner": gr.Textbox.update(visible=False),
            "vcs_url": gr.Textbox.update(visible=False),
            "title": gr.Textbox.update(visible=False),
            "body": gr.Textbox.update(visible=False),
            "base": gr.Textbox.update(visible=False),
            "head": gr.Textbox.update(visible=False),
            "issue_number": gr.Number.update(visible=False),
            "labels": gr.Textbox.update(visible=False),
            "tag": gr.Textbox.update(visible=False),
            "release_name": gr.Textbox.update(visible=False),
            "file_url": gr.Textbox.update(visible=False),
            "repo_url": gr.Textbox.update(visible=False),
            "template_name": gr.Dropdown.update(visible=False),
            "new_description": gr.Textbox.update(visible=False),
            "issue_title": gr.Textbox.update(visible=False),
            "issue_body": gr.Textbox.update(visible=False),
            "issue_state": gr.Dropdown.update(visible=False),
        }

        if action_name in ["import_repository"]:
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "owner": gr.Textbox.update(visible=True), "vcs_url": gr.Textbox.update(visible=True)})
        elif action_name in ["create_repository", "delete_repository", "list_branches", "list_open_pull_requests", "list_issues", "list_closed_issues", "list_releases", "list_forks"]:
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True)})
        elif action_name == "create_project_from_template":
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "template_name": gr.Dropdown.update(visible=True)})
        elif action_name in ["create_file", "get_file", "delete_file", "get_file_content"]:
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "path": gr.Textbox.update(visible=True), "branch": gr.Textbox.update(visible=True)})
            if action_name == "create_file":
                visibility_map.update({"content": gr.Code.update(visible=True), "message": gr.Textbox.update(visible=True)})
        elif action_name == "update_file":
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "path": gr.Textbox.update(visible=True), "branch": gr.Textbox.update(visible=True), "content": gr.Code.update(visible=True), "message": gr.Textbox.update(visible=True)})
        elif action_name == "update_file_diff":
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "path": gr.Textbox.update(visible=True), "branch": gr.Textbox.update(visible=True), "diff": gr.Code.update(visible=True), "diff_message": gr.Textbox.update(visible=True)})
        elif action_name == "get_file_content_by_url":
            visibility_map.update({"file_url": gr.Textbox.update(visible=True)})
        elif action_name in ["create_branch", "delete_branch"]:
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "branch": gr.Textbox.update(visible=True)})
            if action_name == "create_branch":
                visibility_map.update({"base": gr.Textbox.update(visible=True), "head": gr.Textbox.update(visible=True)})
        elif action_name == "create_pull_request":
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "title": gr.Textbox.update(visible=True), "body": gr.Textbox.update(visible=True), "base": gr.Textbox.update(visible=True), "head": gr.Textbox.update(visible=True)})
        elif action_name == "create_issue":
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "title": gr.Textbox.update(visible=True), "body": gr.Textbox.update(visible=True)})
        elif action_name == "add_label_to_issue":
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "issue_number": gr.Number.update(visible=True), "labels": gr.Textbox.update(visible=True)})
        elif action_name in ["close_issue", "add_comment_to_issue", "get_issue_details", "edit_issue"]:
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "issue_number": gr.Number.update(visible=True)})
            if action_name == "add_comment_to_issue":
                visibility_map.update({"message": gr.Textbox.update(visible=True)})
            if action_name == "edit_issue":
                visibility_map.update({"issue_title": gr.Textbox.update(visible=True), "issue_body": gr.Textbox.update(visible=True), "issue_state": gr.Dropdown.update(visible=True)})
        elif action_name == "create_release":
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "tag": gr.Textbox.update(visible=True), "release_name": gr.Textbox.update(visible=True), "message": gr.Textbox.update(visible=True)})
        elif action_name == "fork_repository":
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True)})
        elif action_name in ["list_files", "get_repository_info", "analyze_repository_content"]:
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "owner": gr.Textbox.update(visible=True)})
        elif action_name == "analyze_repository_by_url":
            visibility_map.update({"repo_url": gr.Textbox.update(visible=True)})
        elif action_name == "update_repository_description":
            visibility_map.update({"repo_name": gr.Textbox.update(visible=True), "new_description": gr.Textbox.update(visible=True)})


        return [visibility_map.get(key, gr.Textbox.update(visible=False)) for key in visibility_map]

    output_components_visibility = [
        repo_name, branch, path, content, message, owner, vcs_url, title, body, base, head, issue_number, labels,
        tag, release_name, file_url, repo_url, template_name, new_description, issue_title, issue_body,
        issue_state, diff, diff_message
    ]

    action.change(
        show_hide_input_fields,
        inputs=[action],
        outputs=output_components_visibility
    )


    run_button.click(
        github_tool,
        inputs=input_components,
        outputs=output,
        api_name="github_tool"
    )

demo.launch()