"""GitWorktreeTab widget — git worktree management.

List, create, and remove git worktrees for repositories discovered
under the base directory.  All git operations use ``enriched_env`` for
PATH resolution.
"""

import os
import subprocess

from ai_lsc.utils.process import enriched_env

try:
    from PySide6.QtWidgets import (
        QAbstractItemView,
        QComboBox,
        QHBoxLayout,
        QHeaderView,
        QLabel,
        QLineEdit,
        QPushButton,
        QTableWidget,
        QTableWidgetItem,
        QVBoxLayout,
        QWidget,
    )
    _HAS_QT = True
except ImportError:
    _HAS_QT = False

if _HAS_QT:

    class GitWorktreeTab(QWidget):
        """Git worktree management: list, create, remove worktrees for repos."""

        def __init__(self, main_window):
            super().__init__()
            self.main = main_window
            layout = QVBoxLayout(self)

            header = QHBoxLayout()
            header.addWidget(QLabel("<b>Git Sources — Registry Tool Tracker</b>"))
            header.addStretch()
            self.btn_scan = QPushButton("Scan Repos")
            self.btn_scan.clicked.connect(self.scan_repos)
            header.addWidget(self.btn_scan)
            layout.addLayout(header)

            self.repo_combo = QComboBox()
            self.repo_combo.setPlaceholderText("Select a repository...")
            layout.addWidget(self.repo_combo)

            ctrl = QHBoxLayout()
            self.txt_new_branch = QLineEdit()
            self.txt_new_branch.setPlaceholderText("New branch name for worktree")
            ctrl.addWidget(self.txt_new_branch)
            btn_add = QPushButton("Add Worktree")
            btn_add.setStyleSheet("background-color: #27ae60; color: white;")
            btn_add.clicked.connect(self.add_worktree)
            ctrl.addWidget(btn_add)
            btn_rm = QPushButton("Remove Selected")
            btn_rm.setStyleSheet("background-color: #c0392b; color: white;")
            btn_rm.clicked.connect(self.remove_worktree)
            ctrl.addWidget(btn_rm)
            layout.addLayout(ctrl)

            self.tree_table = QTableWidget(0, 3)
            self.tree_table.setHorizontalHeaderLabels(
                ["Worktree Path", "Branch", "Status"]
            )
            self.tree_table.horizontalHeader().setSectionResizeMode(
                0, QHeaderView.Stretch
            )
            self.tree_table.setSelectionBehavior(QAbstractItemView.SelectRows)
            layout.addWidget(self.tree_table)
            self.scan_repos()

        def scan_repos(self):
            self.repo_combo.clear()
            base = self.main.base_dir
            candidates = [
                d for d in os.listdir(base)
                if os.path.isdir(os.path.join(base, d, ".git"))
            ]
            for repo in candidates:
                self.repo_combo.addItem(repo)

        def _current_repo_path(self) -> str | None:
            name = self.repo_combo.currentText()
            if not name:
                return None
            return os.path.join(self.main.base_dir, name)

        def _run_git(self, args: list[str], cwd: str) -> str:
            env = enriched_env(self.main.base_bin_dir)
            proc = subprocess.run(
                ["git"] + args, capture_output=True, text=True,
                cwd=cwd, env=env, timeout=10,
            )
            return proc.stdout.strip()

        def refresh_table(self):
            repo_path = self._current_repo_path()
            if not repo_path:
                return
            raw = self._run_git(
                ["worktree", "list", "--porcelain"], repo_path
            )
            self.tree_table.setRowCount(0)
            if not raw:
                return
            # UX-13: parse --porcelain key-value format correctly
            current_wt: dict[str, str] = {}
            for line in raw.splitlines():
                if not line.strip():
                    if current_wt.get("worktree") and current_wt.get("branch"):
                        wt_path = current_wt["worktree"]
                        branch = current_wt["branch"].lstrip("[]")
                        status = "locked" if current_wt.get("locked") else "bare" if current_wt.get("bare") else "ok"
                        row = self.tree_table.rowCount()
                        self.tree_table.insertRow(row)
                        self.tree_table.setItem(row, 0, QTableWidgetItem(wt_path))
                        self.tree_table.setItem(row, 1, QTableWidgetItem(branch))
                        self.tree_table.setItem(row, 2, QTableWidgetItem(status))
                    current_wt = {}
                    continue
                if " " in line:
                    key, _, val = line.partition(" ")
                    current_wt[key] = val

        def add_worktree(self):
            repo_path = self._current_repo_path()
            branch = self.txt_new_branch.text().strip()
            if not repo_path or not branch:
                self.main.log("Provide repo and branch name.", "GitWorktree")
                return
            wt_dir = os.path.join(os.path.dirname(repo_path),
                                   f"{os.path.basename(repo_path)}-{branch}")
            self._run_git(
                ["worktree", "add", wt_dir, branch], repo_path
            )
            self.main.log(f"Worktree created: {wt_dir}", "GitWorktree")
            self.txt_new_branch.clear()
            self.refresh_table()

        def remove_worktree(self):
            repo_path = self._current_repo_path()
            row = self.tree_table.currentRow()
            if not repo_path or row < 0:
                return
            wt_path = self.tree_table.item(row, 0).text()
            self._run_git(["worktree", "remove", wt_path], repo_path)
            self.main.log(f"Worktree removed: {wt_path}", "GitWorktree")
            self.refresh_table()

else:
    GitWorktreeTab = None
