import sys
import json
from pathlib import Path

try:
    from PyQt6.QtWidgets import (
        QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
        QPushButton, QLineEdit, QCheckBox, QComboBox, QFrame
    )
    from PyQt6.QtCore import Qt
    from PyQt6.QtGui import QFont
    PYQT_AVAILABLE = True
except ImportError:
    PYQT_AVAILABLE = False


class SettingsWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.config_path = Path.home() / '.includecpp' / '.secret'
        self.config = self._load_config()
        self._setup_ui()
        self._load_values()

    def _load_config(self):
        if self.config_path.exists():
            try:
                return json.loads(self.config_path.read_text())
            except:
                pass
        return {}

    def _save_config(self):
        self.config_path.parent.mkdir(parents=True, exist_ok=True)
        self.config_path.write_text(json.dumps(self.config, indent=2))

    def _setup_ui(self):
        self.setWindowTitle('IncludeCPP Settings')
        self.setFixedSize(340, 520)
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)

        main = QWidget(self)
        main.setGeometry(0, 0, 340, 520)
        main.setStyleSheet('''
            QWidget {
                background-color: #1a1a1a;
                border-radius: 12px;
                color: #e0e0e0;
            }
            QLabel {
                color: #e0e0e0;
                font-size: 12px;
            }
            QLineEdit {
                background-color: #2d2d2d;
                border: 1px solid #3d3d3d;
                border-radius: 6px;
                padding: 10px 12px;
                color: #e0e0e0;
                font-size: 13px;
                min-height: 18px;
            }
            QLineEdit:focus {
                border: 1px solid #4a9eff;
            }
            QPushButton {
                background-color: #2d2d2d;
                border: 1px solid #3d3d3d;
                border-radius: 6px;
                padding: 10px 20px;
                color: #e0e0e0;
                font-size: 13px;
            }
            QPushButton:hover {
                background-color: #3d3d3d;
            }
            QPushButton:pressed {
                background-color: #4a9eff;
            }
            QCheckBox {
                color: #e0e0e0;
                font-size: 13px;
            }
            QCheckBox::indicator {
                width: 18px;
                height: 18px;
                border-radius: 4px;
                background-color: #2d2d2d;
                border: 1px solid #3d3d3d;
            }
            QCheckBox::indicator:checked {
                background-color: #4a9eff;
            }
            QComboBox {
                background-color: #2d2d2d;
                border: 1px solid #3d3d3d;
                border-radius: 6px;
                padding: 10px 12px;
                color: #e0e0e0;
                font-size: 13px;
                min-height: 18px;
            }
            QComboBox::drop-down {
                border: none;
                width: 20px;
            }
            QComboBox QAbstractItemView {
                background-color: #2d2d2d;
                color: #e0e0e0;
                selection-background-color: #4a9eff;
            }
        ''')

        layout = QVBoxLayout(main)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(12)

        header = QHBoxLayout()
        title = QLabel('IncludeCPP')
        title.setFont(QFont('Segoe UI', 14, QFont.Weight.Bold))
        title.setStyleSheet('color: #4a9eff;')
        header.addWidget(title)
        header.addStretch()
        close_btn = QPushButton('×')
        close_btn.setFixedSize(24, 24)
        close_btn.setStyleSheet('font-size: 18px; border-radius: 12px;')
        close_btn.clicked.connect(self.close)
        header.addWidget(close_btn)
        layout.addLayout(header)

        self._add_separator(layout)

        ai_label = QLabel('AI Configuration')
        ai_label.setFont(QFont('Segoe UI', 11, QFont.Weight.Bold))
        layout.addWidget(ai_label)

        self.ai_enabled = QCheckBox('Enable AI Features')
        layout.addWidget(self.ai_enabled)

        layout.addWidget(QLabel('OpenAI API Key'))
        self.api_key = QLineEdit()
        self.api_key.setEchoMode(QLineEdit.EchoMode.Password)
        self.api_key.setPlaceholderText('sk-...')
        layout.addWidget(self.api_key)

        layout.addWidget(QLabel('Model'))
        self.model = QComboBox()
        self.model.addItems(['gpt-5', 'gpt-5-nano', 'gpt-4o', 'gpt-4-turbo', 'gpt-3.5-turbo'])
        layout.addWidget(self.model)

        self._add_separator(layout)

        tokens_label = QLabel('API Tokens')
        tokens_label.setFont(QFont('Segoe UI', 11, QFont.Weight.Bold))
        layout.addWidget(tokens_label)

        layout.addWidget(QLabel('Brave Search API'))
        self.brave_key = QLineEdit()
        self.brave_key.setEchoMode(QLineEdit.EchoMode.Password)
        self.brave_key.setPlaceholderText('Token for --websearch')
        layout.addWidget(self.brave_key)

        self._add_separator(layout)

        limits_label = QLabel('Usage Limits')
        limits_label.setFont(QFont('Segoe UI', 11, QFont.Weight.Bold))
        layout.addWidget(limits_label)

        layout.addWidget(QLabel('Daily Token Limit'))
        self.daily_limit = QLineEdit()
        self.daily_limit.setPlaceholderText('220000')
        layout.addWidget(self.daily_limit)

        layout.addStretch()

        btn_layout = QHBoxLayout()
        save_btn = QPushButton('Save')
        save_btn.setStyleSheet('background-color: #4a9eff;')
        save_btn.clicked.connect(self._save)
        btn_layout.addWidget(save_btn)
        layout.addLayout(btn_layout)

        self._drag_pos = None

    def _add_separator(self, layout):
        line = QFrame()
        line.setFrameShape(QFrame.Shape.HLine)
        line.setStyleSheet('background-color: #3d3d3d; max-height: 1px;')
        layout.addWidget(line)

    def _load_values(self):
        self.ai_enabled.setChecked(self.config.get('enabled', False))
        api = self.config.get('api_key', '')
        if api:
            self.api_key.setText(api)
        model = self.config.get('model', 'gpt-5')
        idx = self.model.findText(model)
        if idx >= 0:
            self.model.setCurrentIndex(idx)
        brave = self.config.get('brave_api_key', '')
        if brave:
            self.brave_key.setText(brave)
        daily_limit = self.config.get('daily_limit', 220000)
        self.daily_limit.setText(str(daily_limit))

    def _save(self):
        self.config['enabled'] = self.ai_enabled.isChecked()
        api = self.api_key.text().strip()
        if api:
            self.config['api_key'] = api
        self.config['model'] = self.model.currentText()
        brave = self.brave_key.text().strip()
        if brave:
            self.config['brave_api_key'] = brave
        limit_text = self.daily_limit.text().strip()
        if limit_text.isdigit() and int(limit_text) >= 1000:
            self.config['daily_limit'] = int(limit_text)
        self._save_config()
        self.close()

    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self._drag_pos = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.MouseButton.LeftButton and self._drag_pos:
            self.move(event.globalPosition().toPoint() - self._drag_pos)
            event.accept()


def show_settings():
    if not PYQT_AVAILABLE:
        return False, 'PyQt6 not installed. Run: pip install PyQt6'
    app = QApplication.instance()
    if not app:
        app = QApplication(sys.argv)
    widget = SettingsWidget()
    widget.show()
    app.exec()
    return True, 'Settings saved'

if __name__ == '__main__':
    success, message = show_settings()
    if not success:
        print(message)