#!/usr/bin/env python3
"""
자동 문서화 시스템
- 작업 완료 시 자동으로 문서 업데이트
- daily 업무일지 자동 업데이트
- 변경 이력 관리
- 진행 상황 추적
"""

import argparse
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional


class AutoDocumenter:
    """자동 문서화 시스템 클래스"""

    def __init__(self, workspace_path: str = "/home/jay/workspace"):
        self.workspace_path = Path(workspace_path)
        self.memory_path = self.workspace_path / "memory"
        self.daily_path = self.memory_path / "daily"
        self.templates_path = self.memory_path / "document-templates.json"
        self.changelog_path = self.memory_path / "CHANGELOG.md"
        self.progress_path = self.memory_path / "progress-tracker.json"

        # 디렉토리 생성
        self.daily_path.mkdir(parents=True, exist_ok=True)

        # 템플릿 로드
        self.templates = self._load_templates()

        # progress-tracker.json 초기화
        if not self.progress_path.exists():
            self._init_progress_tracker()

    def _load_templates(self) -> Dict[str, Any]:
        """템플릿 로드"""
        if self.templates_path.exists():
            with open(self.templates_path, "r", encoding="utf-8") as f:
                return json.load(f)
        else:
            # 기본 템플릿
            return {
                "daily_log": {
                    "header": "# {date} 업무일지\n\n## 완료된 작업\n",
                    "task_template": "- [{time}] {task_type}: {description} - {result}\n",
                },
                "changelog": {
                    "header": "# 변경 이력\n\n## {date}\n",
                    "change_template": "- [{time}] {change_type}: {description}\n",
                },
                "progress": {
                    "header": "# 진행 상황 추적\n\n## 프로젝트 현황\n",
                    "project_template": "### {project}\n- 상태: {status}\n- 마지막 업데이트: {timestamp}\n",
                },
            }

    def _init_progress_tracker(self):
        """progress-tracker.json 초기화"""
        initial_data = {
            "created": datetime.now().isoformat(),
            "projects": {},
            "tasks": [],
            "stats": {"total_tasks": 0, "success_count": 0, "failure_count": 0},
        }
        with open(self.progress_path, "w", encoding="utf-8") as f:
            json.dump(initial_data, f, indent=2, ensure_ascii=False)

    def log_task(self, task_type: str, description: str, result: str = "success") -> bool:
        """
        작업 로그 기록

        Args:
            task_type: 작업 유형 (code, create, update, delete, test 등)
            description: 작업 설명
            result: 작업 결과 (success, failure, partial)

        Returns:
            성공 여부
        """
        try:
            timestamp = datetime.now()
            time_str = timestamp.strftime("%H:%M:%S")
            date_str = timestamp.strftime("%Y-%m-%d")

            # Daily 로그 업데이트
            self._update_daily_log(date_str, time_str, task_type, description, result)

            # Changelog 업데이트
            change_type = f"{task_type}"
            self.update_changelog(change_type, description)

            # Progress tracker 업데이트
            self._update_progress_tracker(task_type, description, result, timestamp)

            print(f"✅ 작업 로그 기록 완료: [{task_type}] {description} - {result}")
            return True

        except Exception as e:
            print(f"❌ 작업 로그 기록 실패: {e}")
            return False

    def _update_daily_log(self, date_str: str, time_str: str, task_type: str, description: str, result: str):
        """Daily 로그 파일 업데이트"""
        daily_file = self.daily_path / f"{date_str}.md"
        template = self.templates["daily_log"]

        # 파일이 없으면 새로 생성
        if not daily_file.exists():
            header = template["header"].format(date=date_str)
            with open(daily_file, "w", encoding="utf-8") as f:
                f.write(header)

        # 작업 내용 추가
        task_entry = template["task_template"].format(
            time=time_str, task_type=task_type, description=description, result=result
        )

        with open(daily_file, "a", encoding="utf-8") as f:
            f.write(task_entry)

    def update_daily_log(self, content: str) -> bool:
        """
        Daily 업무일지 업데이트 (커스텀 내용 추가)

        Args:
            content: 추가할 내용

        Returns:
            성공 여부
        """
        try:
            date_str = datetime.now().strftime("%Y-%m-%d")
            daily_file = self.daily_path / f"{date_str}.md"

            # 파일이 없으면 새로 생성
            if not daily_file.exists():
                template = self.templates["daily_log"]
                header = template["header"].format(date=date_str)
                with open(daily_file, "w", encoding="utf-8") as f:
                    f.write(header)

            # 내용 추가
            with open(daily_file, "a", encoding="utf-8") as f:
                f.write(f"\n{content}\n")

            print(f"✅ Daily 로그 업데이트 완료: {date_str}")
            return True

        except Exception as e:
            print(f"❌ Daily 로그 업데이트 실패: {e}")
            return False

    def update_changelog(self, change_type: str, description: str) -> bool:
        """
        변경 이력 업데이트

        Args:
            change_type: 변경 유형 (added, changed, fixed, removed 등)
            description: 변경 설명

        Returns:
            성공 여부
        """
        try:
            timestamp = datetime.now()
            time_str = timestamp.strftime("%H:%M:%S")
            date_str = timestamp.strftime("%Y-%m-%d")

            template = self.templates["changelog"]

            # 파일이 없으면 새로 생성
            if not self.changelog_path.exists():
                with open(self.changelog_path, "w", encoding="utf-8") as f:
                    f.write("# 변경 이력\n\n")

            # 기존 내용 읽기
            with open(self.changelog_path, "r", encoding="utf-8") as f:
                content = f.read()

            # 오늘 날짜 섹션이 있는지 확인
            date_header = f"## {date_str}"

            change_entry = template["change_template"].format(
                time=time_str, change_type=change_type, description=description
            )

            if date_header in content:
                # 오늘 날짜 섹션에 추가
                lines = content.split("\n")
                insert_index = 0
                for i, line in enumerate(lines):
                    if line == date_header:
                        insert_index = i + 1
                        break

                lines.insert(insert_index, change_entry.rstrip("\n"))
                content = "\n".join(lines)
            else:
                # 새로운 날짜 섹션 추가 (맨 위에)
                new_section = f"\n## {date_str}\n{change_entry}"
                # 첫 번째 섹션 바로 뒤에 삽입
                if content.startswith("# 변경 이력\n\n"):
                    content = content.replace("# 변경 이력\n\n", f"# 변경 이력\n\n{new_section}\n\n", 1)
                else:
                    content = f"# 변경 이력\n\n{new_section}\n\n" + content[len("# 변경 이력\n\n") :]

            # 파일 쓰기
            with open(self.changelog_path, "w", encoding="utf-8") as f:
                f.write(content)

            return True

        except Exception as e:
            print(f"❌ Changelog 업데이트 실패: {e}")
            return False

    def _update_progress_tracker(self, task_type: str, description: str, result: str, timestamp: datetime):
        """Progress tracker 업데이트"""
        try:
            with open(self.progress_path, "r", encoding="utf-8") as f:
                data = json.load(f)

            # 작업 추가
            task_entry = {
                "timestamp": timestamp.isoformat(),
                "type": task_type,
                "description": description,
                "result": result,
            }
            data["tasks"].append(task_entry)

            # 통계 업데이트
            data["stats"]["total_tasks"] += 1
            if result == "success":
                data["stats"]["success_count"] += 1
            elif result == "failure":
                data["stats"]["failure_count"] += 1

            # 최근 1000개 작업만 유지
            if len(data["tasks"]) > 1000:
                data["tasks"] = data["tasks"][-1000:]

            with open(self.progress_path, "w", encoding="utf-8") as f:
                json.dump(data, f, indent=2, ensure_ascii=False)

        except Exception as e:
            print(f"⚠️ Progress tracker 업데이트 실패: {e}")

    def track_progress(self, project: str, status: str) -> bool:
        """
        진행 상황 추적

        Args:
            project: 프로젝트 이름
            status: 프로젝트 상태 (active, completed, on-hold, cancelled)

        Returns:
            성공 여부
        """
        try:
            with open(self.progress_path, "r", encoding="utf-8") as f:
                data = json.load(f)

            timestamp = datetime.now().isoformat()

            # 프로젝트 상태 업데이트
            if project not in data["projects"]:
                data["projects"][project] = {
                    "status": status,
                    "created": timestamp,
                    "last_updated": timestamp,
                    "history": [],
                }
            else:
                data["projects"][project]["status"] = status
                data["projects"][project]["last_updated"] = timestamp

            # 상태 변경 이력 추가
            data["projects"][project]["history"].append({"status": status, "timestamp": timestamp})

            with open(self.progress_path, "w", encoding="utf-8") as f:
                json.dump(data, f, indent=2, ensure_ascii=False)

            print(f"✅ 프로젝트 진행 상황 업데이트: {project} → {status}")
            return True

        except Exception as e:
            print(f"❌ 진행 상황 추적 실패: {e}")
            return False

    def generate_summary(self, date: Optional[str] = None) -> str:
        """
        요약 생성

        Args:
            date: 요약할 날짜 (YYYY-MM-DD), None이면 오늘

        Returns:
            요약 문자열
        """
        try:
            if date is None:
                date = datetime.now().strftime("%Y-%m-%d")

            # Progress tracker에서 통계 가져오기
            with open(self.progress_path, "r", encoding="utf-8") as f:
                data = json.load(f)

            stats = data["stats"]

            # 오늘 작업 필터링
            today_tasks = [task for task in data["tasks"] if task["timestamp"].startswith(date)]

            # 오늘 통계 계산
            today_success = sum(1 for t in today_tasks if t["result"] == "success")
            today_failure = sum(1 for t in today_tasks if t["result"] == "failure")

            # 주요 작업 추출
            major_tasks = "\n".join([f"- [{t['type']}] {t['description']}" for t in today_tasks[:10]])  # 최대 10개

            summary = f"""# {date} 요약

## 오늘의 통계
- 총 작업 수: {len(today_tasks)}
- 성공: {today_success}
- 실패: {today_failure}

## 주요 작업
{major_tasks if major_tasks else "- 기록된 작업 없음"}

## 전체 통계
- 총 작업 수: {stats['total_tasks']}
- 총 성공: {stats['success_count']}
- 총 실패: {stats['failure_count']}
"""

            return summary

        except Exception as e:
            return f"❌ 요약 생성 실패: {e}"


def main():
    """CLI 인터페이스"""
    parser = argparse.ArgumentParser(
        description="자동 문서화 시스템",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # 작업 로그 기록
  python3 auto-document.py log --type "code" --desc "Modified skill-router.py" --result "success"
  
  # Daily 로그에 커스텀 내용 추가
  python3 auto-document.py daily --content "오늘의 특이사항: ..."
  
  # Changelog 업데이트
  python3 auto-document.py changelog --type "added" --desc "New feature added"
  
  # 진행 상황 추적
  python3 auto-document.py progress --project "my-project" --status "active"
  
  # 요약 생성
  python3 auto-document.py summary --date "2025-02-27"
        """,
    )

    subparsers = parser.add_subparsers(dest="command", help="사용 가능한 명령어")

    # log 명령어
    log_parser = subparsers.add_parser("log", help="작업 로그 기록")
    log_parser.add_argument("--type", required=True, help="작업 유형 (code, create, update, delete, test 등)")
    log_parser.add_argument("--desc", required=True, help="작업 설명")
    log_parser.add_argument("--result", default="success", help="작업 결과 (success, failure, partial)")

    # daily 명령어
    daily_parser = subparsers.add_parser("daily", help="Daily 업무일지 업데이트")
    daily_parser.add_argument("--content", required=True, help="추가할 내용")

    # changelog 명령어
    changelog_parser = subparsers.add_parser("changelog", help="변경 이력 업데이트")
    changelog_parser.add_argument("--type", required=True, help="변경 유형 (added, changed, fixed, removed 등)")
    changelog_parser.add_argument("--desc", required=True, help="변경 설명")

    # progress 명령어
    progress_parser = subparsers.add_parser("progress", help="진행 상황 추적")
    progress_parser.add_argument("--project", required=True, help="프로젝트 이름")
    progress_parser.add_argument(
        "--status", required=True, help="프로젝트 상태 (active, completed, on-hold, cancelled)"
    )

    # summary 명령어
    summary_parser = subparsers.add_parser("summary", help="요약 생성")
    summary_parser.add_argument("--date", help="요약할 날짜 (YYYY-MM-DD), 기본값: 오늘")

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        return

    doc = AutoDocumenter()

    if args.command == "log":
        doc.log_task(args.type, args.desc, args.result)
    elif args.command == "daily":
        doc.update_daily_log(args.content)
    elif args.command == "changelog":
        doc.update_changelog(args.type, args.desc)
    elif args.command == "progress":
        doc.track_progress(args.project, args.status)
    elif args.command == "summary":
        print(doc.generate_summary(args.date))


if __name__ == "__main__":
    main()
