import sys
import os
import hashlib
import shutil
import threading
import time
from datetime import datetime, timedelta

from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget,
    QFileDialog, QProgressBar, QLabel, QTextEdit, QHBoxLayout, QFrame,
    QScrollArea, QSizePolicy, QSpacerItem
)
from PyQt5.QtCore import Qt, pyqtSignal, QObject, QTimer, QPropertyAnimation, QEasingCurve, QRect
from PyQt5.QtGui import QFont, QPalette, QColor, QIcon

LOG_FILE = 'backup_log.txt'
HISTORY_FILE = 'backup_history.txt'
MAX_BACKUPS = 5  # 자동 정리: 최대 백업본 개수

def file_hash(path):
    """파일의 SHA256 해시값 계산 (중복 체크용)"""
    h = hashlib.sha256()
    with open(path, 'rb') as f:
        while chunk := f.read(8192):
            h.update(chunk)
    return h.hexdigest()

class ModernProgressBar(QProgressBar):
    def __init__(self):
        super().__init__()
        self.setStyleSheet("""
            QProgressBar {
                border: none;
                border-radius: 8px;
                text-align: center;
                background: #2d3748;
                color: #e2e8f0;
                font-weight: 600;
                height: 16px;
            }
            QProgressBar::chunk {
                border-radius: 8px;
                background: qlineargradient(
                    x1:0, y1:0, x2:1, y2:0,
                    stop:0 #667eea,
                    stop:1 #764ba2
                );
            }
        """)

class BackupWorker(QObject):
    progress = pyqtSignal(int)
    file_copied = pyqtSignal(str)
    status = pyqtSignal(str)
    finished = pyqtSignal()
    stopped = pyqtSignal()

    def __init__(self, src, dst, pause_event, stop_event):
        super().__init__()
        self.src = src
        self.dst = dst
        self.pause_event = pause_event
        self.stop_event = stop_event

    def run(self):
        try:
            self.status.emit("📂 파일 리스트 수집 중...")
            file_list = []
            for root, dirs, files in os.walk(self.src):
                for name in files:
                    full = os.path.join(root, name)
                    rel = os.path.relpath(full, self.src)
                    file_list.append(rel)
            total = len(file_list)
            copied = 0

            # 히스토리 불러오기 (중복, 증분 체크)
            old_hashes = self._load_backup_history()

            # 새 백업본 폴더 (타임스탬프)
            backup_name = datetime.now().strftime('%Y%m%d_%H%M%S')
            backup_path = os.path.join(self.dst, backup_name)
            os.makedirs(backup_path, exist_ok=True)
            self.status.emit(f"📁 백업 폴더 생성: {backup_name}")

            new_hashes = {}

            for idx, rel_path in enumerate(file_list):
                src_file = os.path.join(self.src, rel_path)
                dst_file = os.path.join(backup_path, rel_path)

                if self.stop_event.is_set():
                    self.status.emit("🛑 백업 중지됨")
                    self.stopped.emit()
                    return

                self.pause_event.wait()  # 일시정지 시 block

                # 파일 해시로 변경 여부 확인 (증분/중복)
                hash_val = file_hash(src_file)
                new_hashes[rel_path] = hash_val
                if rel_path in old_hashes and old_hashes[rel_path] == hash_val:
                    self.status.emit(f"⏭️ {rel_path}")
                else:
                    os.makedirs(os.path.dirname(dst_file), exist_ok=True)
                    shutil.copy2(src_file, dst_file)
                    self.file_copied.emit(rel_path)
                    self.status.emit(f"✅ {rel_path}")

                copied += 1
                progress = int(copied / total * 100)
                self.progress.emit(progress)

            self._save_backup_history(new_hashes)
            self.status.emit("🎉 백업 완료!")
            self._auto_cleanup()
            self.finished.emit()
        except Exception as e:
            self.status.emit(f"❌ 오류 발생: {e}")
            self.finished.emit()

    def _load_backup_history(self):
        if not os.path.exists(HISTORY_FILE):
            return {}
        try:
            with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                return dict(line.strip().split('\t') for line in lines if '\t' in line)
        except:
            return {}

    def _save_backup_history(self, hashes):
        with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
            for rel, hashv in hashes.items():
                f.write(f"{rel}\t{hashv}\n")

    def _auto_cleanup(self):
        """MAX_BACKUPS 초과시 가장 오래된 백업 삭제"""
        try:
            backups = sorted([
                d for d in os.listdir(self.dst)
                if os.path.isdir(os.path.join(self.dst, d))
            ])
            if len(backups) > MAX_BACKUPS:
                for b in backups[:-MAX_BACKUPS]:
                    b_path = os.path.join(self.dst, b)
                    shutil.rmtree(b_path)
                    self.status.emit(f"🗑️ 오래된 백업 삭제: {b}")
        except Exception as e:
            self.status.emit(f"⚠️ 정리 오류: {e}")

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("BackupPro - 스마트 증분 백업")
        self.setFixedSize(800, 600)
        
        # 어플리케이션 스타일 설정
        self.setStyleSheet(self.get_app_style())

        self.src_dir = ""
        self.dst_dir = ""
        self.backup_thread = None
        self.worker = None
        self.pause_event = threading.Event()
        self.pause_event.set()
        self.stop_event = threading.Event()
        self.timer = QTimer()
        self.timer.timeout.connect(self.scheduled_backup)

        self.setup_ui()
        self.scheduled = False

    def get_app_style(self):
        return """
        QMainWindow {
            background: qlineargradient(
                x1:0, y1:0, x2:0, y2:1,
                stop:0 #1a202c,
                stop:1 #2d3748
            );
            color: #e2e8f0;
        }
        
        QWidget {
            background: transparent;
            color: #e2e8f0;
            font-family: 'Segoe UI', 'Apple SD Gothic Neo', sans-serif;
        }
        
        QPushButton {
            background: qlineargradient(
                x1:0, y1:0, x2:0, y2:1,
                stop:0 #4299e1,
                stop:1 #3182ce
            );
            border: none;
            border-radius: 12px;
            color: white;
            font-weight: 600;
            font-size: 14px;
            padding: 12px 24px;
            min-height: 20px;
        }
        
        QPushButton:hover {
            background: qlineargradient(
                x1:0, y1:0, x2:0, y2:1,
                stop:0 #63b3ed,
                stop:1 #4299e1
            );
            transform: translateY(-2px);
        }
        
        QPushButton:pressed {
            background: qlineargradient(
                x1:0, y1:0, x2:0, y2:1,
                stop:0 #2c5282,
                stop:1 #2a69ac
            );
        }
        
        QPushButton#primaryBtn {
            background: qlineargradient(
                x1:0, y1:0, x2:1, y2:0,
                stop:0 #667eea,
                stop:1 #764ba2
            );
        }
        
        QPushButton#primaryBtn:hover {
            background: qlineargradient(
                x1:0, y1:0, x2:1, y2:0,
                stop:0 #7c3aed,
                stop:1 #8b5cf6
            );
        }
        
        QPushButton#warningBtn {
            background: qlineargradient(
                x1:0, y1:0, x2:0, y2:1,
                stop:0 #f6ad55,
                stop:1 #ed8936
            );
        }
        
        QPushButton#dangerBtn {
            background: qlineargradient(
                x1:0, y1:0, x2:0, y2:1,
                stop:0 #fc8181,
                stop:1 #e53e3e
            );
        }
        
        QPushButton#successBtn {
            background: qlineargradient(
                x1:0, y1:0, x2:0, y2:1,
                stop:0 #68d391,
                stop:1 #38a169
            );
        }
        
        QLabel {
            color: #cbd5e0;
            font-size: 14px;
            font-weight: 500;
        }
        
        QLabel#titleLabel {
            color: #e2e8f0;
            font-size: 18px;
            font-weight: 700;
            margin: 10px 0;
        }
        
        QLabel#pathLabel {
            background: #2d3748;
            border: 2px solid #4a5568;
            border-radius: 8px;
            padding: 8px 12px;
            color: #a0aec0;
            font-family: 'Consolas', 'Monaco', monospace;
        }
        
        QTextEdit {
            background: #1a202c;
            border: 2px solid #2d3748;
            border-radius: 12px;
            padding: 12px;
            color: #e2e8f0;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 12px;
            selection-background-color: #4a5568;
        }
        
        QFrame#card {
            background: rgba(45, 55, 72, 0.8);
            border: 1px solid #4a5568;
            border-radius: 16px;
            margin: 8px;
        }
        
        QScrollBar:vertical {
            background: #2d3748;
            width: 12px;
            border-radius: 6px;
        }
        
        QScrollBar::handle:vertical {
            background: #4a5568;
            border-radius: 6px;
            min-height: 20px;
        }
        
        QScrollBar::handle:vertical:hover {
            background: #718096;
        }
        """

    def setup_ui(self):
        central = QWidget()
        main_layout = QVBoxLayout(central)
        main_layout.setSpacing(20)
        main_layout.setContentsMargins(30, 30, 30, 30)

        # 타이틀
        title = QLabel("BackupPro")
        title.setObjectName("titleLabel")
        title.setAlignment(Qt.AlignCenter)
        main_layout.addWidget(title)

        # 폴더 선택 카드
        folder_card = QFrame()
        folder_card.setObjectName("card")
        folder_layout = QVBoxLayout(folder_card)
        folder_layout.setContentsMargins(20, 20, 20, 20)

        folder_title = QLabel("📁 폴더 설정")
        folder_title.setObjectName("titleLabel")
        folder_layout.addWidget(folder_title)

        # 원본 폴더
        src_layout = QVBoxLayout()
        src_label = QLabel("원본 폴더:")
        self.src_path_label = QLabel("폴더를 선택해주세요")
        self.src_path_label.setObjectName("pathLabel")
        self.btn_src = QPushButton("📂 원본 폴더 선택")
        
        src_layout.addWidget(src_label)
        src_layout.addWidget(self.src_path_label)
        src_layout.addWidget(self.btn_src)
        folder_layout.addLayout(src_layout)

        # 백업 폴더
        dst_layout = QVBoxLayout()
        dst_label = QLabel("백업 폴더:")
        self.dst_path_label = QLabel("폴더를 선택해주세요")
        self.dst_path_label.setObjectName("pathLabel")
        self.btn_dst = QPushButton("💾 백업 폴더 선택")
        
        dst_layout.addWidget(dst_label)
        dst_layout.addWidget(self.dst_path_label)
        dst_layout.addWidget(self.btn_dst)
        folder_layout.addLayout(dst_layout)

        main_layout.addWidget(folder_card)

        # 컨트롤 카드
        control_card = QFrame()
        control_card.setObjectName("card")
        control_layout = QVBoxLayout(control_card)
        control_layout.setContentsMargins(20, 20, 20, 20)

        control_title = QLabel("⚙️ 백업 제어")
        control_title.setObjectName("titleLabel")
        control_layout.addWidget(control_title)

        # 버튼들
        btn_layout = QHBoxLayout()
        btn_layout.setSpacing(12)

        self.btn_start = QPushButton("▶️ 시작")
        self.btn_start.setObjectName("primaryBtn")
        
        self.btn_pause = QPushButton("⏸️ 일시정지")
        self.btn_pause.setObjectName("warningBtn")
        
        self.btn_stop = QPushButton("⏹️ 중지")
        self.btn_stop.setObjectName("dangerBtn")
        
        self.btn_schedule = QPushButton("🕐 5분마다 자동 백업")
        self.btn_schedule.setObjectName("successBtn")

        btn_layout.addWidget(self.btn_start)
        btn_layout.addWidget(self.btn_pause)
        btn_layout.addWidget(self.btn_stop)
        btn_layout.addWidget(self.btn_schedule)
        
        control_layout.addLayout(btn_layout)

        # 프로그레스 바
        progress_layout = QVBoxLayout()
        progress_label = QLabel("진행 상황:")
        self.progress = ModernProgressBar()
        self.progress.setValue(0)
        
        progress_layout.addWidget(progress_label)
        progress_layout.addWidget(self.progress)
        control_layout.addLayout(progress_layout)

        # 현재 파일
        self.label_file = QLabel("대기 중...")
        self.label_file.setObjectName("pathLabel")
        control_layout.addWidget(self.label_file)

        main_layout.addWidget(control_card)

        # 로그 카드
        log_card = QFrame()
        log_card.setObjectName("card")
        log_layout = QVBoxLayout(log_card)
        log_layout.setContentsMargins(20, 20, 20, 20)

        log_title = QLabel("📋 실시간 로그")
        log_title.setObjectName("titleLabel")
        log_layout.addWidget(log_title)

        self.text_status = QTextEdit()
        self.text_status.setReadOnly(True)
        self.text_status.setMaximumHeight(200)
        log_layout.addWidget(self.text_status)

        main_layout.addWidget(log_card)

        self.setCentralWidget(central)

        # 시그널 연결
        self.btn_src.clicked.connect(self.select_src)
        self.btn_dst.clicked.connect(self.select_dst)
        self.btn_start.clicked.connect(self.start_backup)
        self.btn_pause.clicked.connect(self.pause_resume)
        self.btn_stop.clicked.connect(self.stop_backup)
        self.btn_schedule.clicked.connect(self.toggle_schedule)

    def select_src(self):
        d = QFileDialog.getExistingDirectory(self, "원본 폴더 선택")
        if d:
            self.src_dir = d
            self.src_path_label.setText(d)
            self.log_status(f"✅ 원본 폴더 설정: {self.src_dir}")

    def select_dst(self):
        d = QFileDialog.getExistingDirectory(self, "백업 폴더 선택")
        if d:
            self.dst_dir = d
            self.dst_path_label.setText(d)
            self.log_status(f"✅ 백업 폴더 설정: {self.dst_dir}")

    def start_backup(self):
        if not self.src_dir or not self.dst_dir:
            self.log_status("⚠️ 원본/백업 폴더를 모두 선택해주세요.")
            return
        
        self.log_status("🚀 백업을 시작합니다!")
        self.progress.setValue(0)
        self.stop_event.clear()
        self.pause_event.set()
        
        self.worker = BackupWorker(self.src_dir, self.dst_dir, self.pause_event, self.stop_event)
        self.worker.progress.connect(self.progress.setValue)
        self.worker.file_copied.connect(self.update_current_file)
        self.worker.status.connect(self.log_status)
        self.worker.finished.connect(self.backup_done)
        self.worker.stopped.connect(self.backup_stopped)

        self.backup_thread = threading.Thread(target=self.worker.run, daemon=True)
        self.backup_thread.start()

    def update_current_file(self, filename):
        self.label_file.setText(f"📄 {filename}")

    def pause_resume(self):
        if not self.worker:
            return
        if self.pause_event.is_set():
            self.pause_event.clear()
            self.btn_pause.setText("▶️ 재개")
            self.log_status("⏸️ 백업이 일시정지되었습니다.")
        else:
            self.pause_event.set()
            self.btn_pause.setText("⏸️ 일시정지")
            self.log_status("▶️ 백업을 재개합니다.")

    def stop_backup(self):
        if self.worker:
            self.stop_event.set()
            self.pause_event.set()
            self.log_status("🛑 백업 중지를 요청했습니다.")

    def backup_done(self):
        self.log_status("🎉 백업이 성공적으로 완료되었습니다!")
        self.label_file.setText("✅ 백업 완료")
        self.worker = None

    def backup_stopped(self):
        self.log_status("⏹️ 백업이 사용자에 의해 중지되었습니다.")
        self.label_file.setText("⏹️ 백업 중지됨")
        self.worker = None

    def log_status(self, msg):
        now = datetime.now().strftime("%H:%M:%S")
        line = f"[{now}] {msg}"
        self.text_status.append(line)
        
        # 로그 파일에도 저장
        with open(LOG_FILE, 'a', encoding='utf-8') as f:
            f.write(line + '\n')
        
        # 스크롤을 맨 아래로
        scrollbar = self.text_status.verticalScrollBar()
        scrollbar.setValue(scrollbar.maximum())

    def toggle_schedule(self):
        if self.scheduled:
            self.timer.stop()
            self.scheduled = False
            self.btn_schedule.setText("🕐 5분마다 자동 백업")
            self.log_status("⏰ 자동 백업 스케줄이 중지되었습니다.")
        else:
            self.timer.start(5 * 60 * 1000)  # 5분
            self.scheduled = True
            self.btn_schedule.setText("⏰ 스케줄 중지")
            self.log_status("⏰ 5분마다 자동 백업이 시작되었습니다.")

    def scheduled_backup(self):
        if not self.worker and self.src_dir and self.dst_dir:
            self.log_status("🤖 자동 백업이 실행됩니다.")
            self.start_backup()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 폰트 설정
    font = QFont("Segoe UI", 10)
    app.setFont(font)
    
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())