#!/usr/bin/env python3
"""AI-WORKS 프로젝트 생성기 - 1단계 버전"""

import os
import re
import shutil
import sys
from pathlib import Path
from datetime import datetime

# UTF-8 인코딩 강제 (Windows 콘솔 호환)
if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')
    sys.stderr.reconfigure(encoding='utf-8')
    if hasattr(sys.stdin, 'reconfigure'):
        sys.stdin.reconfigure(encoding='utf-8')


def get_template_folder() -> Path:
    """템플릿 폴더 경로 반환 (EXE/개발 모두 지원)"""
    # 1. 현재 작업 폴더 기준
    cwd_template = Path.cwd() / "templates" / "default"
    if cwd_template.is_dir():
        return cwd_template
    
    # 2. EXE 파일이 있는 폴더의 부모 폴더 기준 (dist 안에 있으면)
    if getattr(sys, 'frozen', False):
        exe_folder = Path(sys.executable).parent
        if exe_folder.name == "dist":
            parent_template = exe_folder.parent / "templates" / "default"
            if parent_template.is_dir():
                return parent_template
        # EXE 파일이 있는 폴더 기준
        exe_template = exe_folder / "templates" / "default"
        if exe_template.is_dir():
            return exe_template
    
    # 3. create_project.py 파일 위치 기준
    script_template = Path(__file__).parent / "templates" / "default"
    return script_template


def get_project_number() -> str:
    """프로젝트 번호 입력받기"""
    while True:
        number = input("프로젝트 번호 (예: 03): ").strip()
        if not number:
            print("오류: 프로젝트 번호를 입력해주세요.")
            continue
        if not number.isdigit():
            print("오류: 프로젝트 번호는 숫자만 입력해주세요.")
            continue
        return number


def get_project_name() -> str:
    """프로젝트 이름 입력받기"""
    while True:
        name = input("프로젝트 이름 (예: 사진분류): ").strip()
        if not name:
            print("오류: 프로젝트 이름을 입력해주세요.")
            continue
        return name


def substitute_template_vars(content: str, project_number: str, project_name: str, created_date: str) -> str:
    """템플릿 변수 치환"""
    content = content.replace("{PROJECT_NAME}", project_name)
    content = content.replace("{PROJECT_NUMBER}", project_number)
    content = content.replace("{CREATED_DATE}", created_date)
    return content


def create_project_structure(project_number: str, project_name: str) -> bool:
    """프로젝트 폴더 구조 생성"""
    base_path = Path(r"D:\AI-WORKS")
    project_folder = base_path / f"{project_number}-{project_name}"
    
    # 이미 존재하는지 확인
    if project_folder.exists():
        print(f"오류: 이미 존재하는 프로젝트 폴더입니다: {project_folder}")
        return False
    
    # 프로젝트 폴더 생성
    try:
        project_folder.mkdir(parents=True, exist_ok=False)
        print(f"생성됨: {project_folder}")
    except Exception as e:
        print(f"오류: 프로젝트 폴더 생성 실패 - {e}")
        return False
    
    # 하위 폴더 생성
    sub_folders = ["source", "output", "backup", "logs", "src"]
    for folder in sub_folders:
        folder_path = project_folder / folder
        try:
            folder_path.mkdir(exist_ok=False)
            print(f"생성됨: {folder_path}")
        except Exception as e:
            print(f"오류: 하위 폴더 생성 실패 - {e}")
            return False
    
    return True


def copy_templates(project_number: str, project_name: str) -> bool:
    """템플릿 파일 복사 및 변수 치환"""
    base_path = Path(r"D:\AI-WORKS")
    project_folder = base_path / f"{project_number}-{project_name}"
    template_folder = get_template_folder()
    created_date = datetime.now().strftime("%Y-%m-%d")

    template_files = [
        "AI-WORKS_START.md.template",
        "AI-WORKS_MASTER.md.template",
        "AI-WORKS_HISTORY.md.template",
        "AI-WORKS_DECISIONS.md.template",
        "AI-WORKS_GLOSSARY.md.template",
        "AI-WORKS_GPT_START_PROMPT.md.template",
        "AI-WORKS_AI_REQUEST.md.template",
        "PROJECT_CONTEXT.md.template",
        "RULES.md.template",
        "README.md.template",
        "CHANGELOG.md.template",
        "TODO.md.template",
        "SESSION.md.template",
        "IDEA.md.template",
        "STATE.json.template",
        "config.json.template",
        "run.bat.template",
        "build_exe.bat.template",
        "REQUIREMENTS.md.template",
        "TECHNICAL_DECISIONS.md.template",
        "UI_FLOW.md.template",
        "ARCHITECTURE.md.template",
        "IMPLEMENTATION_PLAN.md.template",
        "DESIGN_FREEZE.md.template",
        "DOCUMENT_VALIDATION_RULES.md.template",
    ]

    for template_file in template_files:
        src_file = template_folder / template_file
        dest_file = project_folder / template_file.replace(".template", "")
        
        try:
            content = src_file.read_text(encoding="utf-8")
            content = substitute_template_vars(content, project_number, project_name, created_date)
            dest_file.write_text(content, encoding="utf-8")
            print(f"복사됨: {dest_file.name}")
        except Exception as e:
            print(f"오류: 템플릿 복사 실패 - {e}")
            return False
    
    return True


def confirm_creation(project_number: str, project_name: str) -> bool:
    """프로젝트 생성 전 확인"""
    base_path = Path(r"D:\AI-WORKS")
    project_folder = base_path / f"{project_number}-{project_name}"
    
    print("\n" + "=" * 50)
    print("생성 예정 프로젝트")
    print("=" * 50)
    print(f"\n프로젝트 경로")
    print(f"\nD:\\AI-WORKS\\{project_number}-{project_name}")
    print(f"\n생성될 폴더")
    
    sub_folders = ["source", "output", "backup", "logs", "src"]
    for folder in sub_folders:
        print(f"[OK] {folder}")
    
    print("\n" + "=" * 50)
    
    while True:
        choice = input("\n계속하시겠습니까?\nY = 생성\nN = 종료\n선택 : ").strip().upper()
        if choice in ("Y"):
            return True
        elif choice in ("N"):
            print("작업을 취소했습니다.")
            return False
        else:
            print("잘못된 입력입니다.")


def check_templates_exist() -> bool:
    """템플릿 파일 존재 여부 확인"""
    template_folder = get_template_folder()

    if not template_folder.is_dir():
        print("오류: templates/default 폴더가 없습니다.")
        print("프로젝트 생성을 중단합니다.")
        return False

    template_files = [
        "AI-WORKS_START.md.template",
        "AI-WORKS_MASTER.md.template",
        "AI-WORKS_HISTORY.md.template",
        "AI-WORKS_DECISIONS.md.template",
        "AI-WORKS_GLOSSARY.md.template",
        "AI-WORKS_GPT_START_PROMPT.md.template",
        "AI-WORKS_AI_REQUEST.md.template",
        "PROJECT_CONTEXT.md.template",
        "RULES.md.template",
        "README.md.template",
        "CHANGELOG.md.template",
        "TODO.md.template",
        "SESSION.md.template",
        "IDEA.md.template",
        "STATE.json.template",
        "config.json.template",
        "run.bat.template",
        "build_exe.bat.template",
        "REQUIREMENTS.md.template",
        "TECHNICAL_DECISIONS.md.template",
        "UI_FLOW.md.template",
        "ARCHITECTURE.md.template",
        "IMPLEMENTATION_PLAN.md.template",
        "DESIGN_FREEZE.md.template",
        "DOCUMENT_VALIDATION_RULES.md.template",
    ]
    
    missing_files = []
    for template_file in template_files:
        if not (template_folder / template_file).exists():
            missing_files.append(template_file)
    
    if missing_files:
        print("오류: 필수 템플릿 파일이 없습니다.")
        print("누락 파일:")
        for f in missing_files:
            print(f"- templates/default/{f}")
        print("프로젝트 생성을 중단합니다.")
        return False
    
    return True


def rollback_project(project_number: str, project_name: str) -> bool:
    """프로젝트 생성 실패 시 Rollback"""
    base_path = Path(r"D:\AI-WORKS")
    project_folder = base_path / f"{project_number}-{project_name}"
    
    try:
        print(f"\n프로젝트 생성 중 오류가 발생했습니다.")
        print(f"생성된 불완전한 프로젝트를 삭제합니다.")
        shutil.rmtree(project_folder)
        print(f"\nRollback 완료:")
        print(f"{project_folder}")
        print(f"\n작업을 중단합니다.")
        return True
    except Exception as e:
        print(f"\nRollback 실패: {e}")
        return False


def validate_documents(project_folder: Path) -> dict:
    """문서 내용 검증"""
    results = {
        "valid": True,
        "errors": [],
        "warnings": [],
        "details": []
    }

    doc_rules = {
        "PROJECT_CONTEXT.md": {"min_length": 100, "required_sections": ["프로젝트 개요", "다음 단계"]},
        "TODO.md": {"min_length": 100, "required_sections": ["작업 목록"]},
        "REQUIREMENTS.md": {"min_length": 500, "required_sections": ["핵심 요구사항"]},
        "TECHNICAL_DECISIONS.md": {"min_length": 500, "required_sections": ["기술 결정"]},
        "UI_FLOW.md": {"min_length": 500, "required_sections": ["사용자 인터페이스 흐름"]},
        "ARCHITECTURE.md": {"min_length": 500, "required_sections": ["아키텍처"]},
        "IMPLEMENTATION_PLAN.md": {"min_length": 200, "required_sections": ["구현 계획"]},
        "DESIGN_FREEZE.md": {"min_length": 100, "required_sections": ["설계 확정"]},
        "DOCUMENT_VALIDATION_RULES.md": {"min_length": 100, "required_sections": ["문서 검증 규칙"]},
        "SESSION.md": {"min_length": 50, "required_sections": ["세션 정보"]},
        "STATE.json": {"min_length": 50, "required_sections": ["project", "current_phase"]},
        "RULES.md": {"min_length": 100, "required_sections": ["문서 작성 규칙"]},
        "README.md": {"min_length": 100, "required_sections": ["사용법"]},
        "CHANGELOG.md": {"min_length": 50, "required_sections": ["Changelog"]},
        "IDEA.md": {"min_length": 50, "required_sections": ["IDEA"]},
        "config.json": {"min_length": 30, "required_sections": ["project"]},
    }

    placeholder_patterns = [
        "내용을 입력하세요",
        r"\bTODO\b",
        r"\bplaceholder\b",
        r"\bN/A\b",
    ]

    for doc_name, rules in doc_rules.items():
        doc_path = project_folder / doc_name
        if not doc_path.exists():
            results["errors"].append(f"문서 없음: {doc_name}")
            results["valid"] = False
            continue

        try:
            content = doc_path.read_text(encoding="utf-8")
        except Exception as e:
            results["errors"].append(f"문서 읽기 실패: {doc_name} ({e})")
            results["valid"] = False
            continue

        if len(content) < rules["min_length"]:
            results["warnings"].append(f"길이 부족: {doc_name} ({len(content)}자, 최소 {rules['min_length']}자)")
            results["details"].append(f"[WARNING] {doc_name}: 길이 부족")

        for pattern in placeholder_patterns:
            if re.search(pattern, content):
                results["errors"].append(f"placeholder 발견: {doc_name} ('{pattern}')")
                results["valid"] = False
                results["details"].append(f"[FAIL] {doc_name}: placeholder 발견 ('{pattern}')")
                break

        lines = content.splitlines()
        section_found = {section: False for section in rules["required_sections"]}
        for line in lines:
            for section in rules["required_sections"]:
                if section in line:
                    section_found[section] = True
        
        missing_sections = [s for s, found in section_found.items() if not found]
        if missing_sections:
            results["warnings"].append(f"필수 섹션 부족: {doc_name} ({', '.join(missing_sections)})")
            results["details"].append(f"[WARNING] {doc_name}: 필수 섹션 부족")

        if doc_name not in [e.split(":")[0] for e in results["errors"]]:
            if not any(doc_name in d for d in results["details"]):
                results["details"].append(f"[PASS] {doc_name}: 검증 통과")

    return results


def save_log(project_number: str, project_name: str, status: str) -> None:
    """생성 로그 저장"""
    log_folder = Path(__file__).parent / "logs"
    log_folder.mkdir(exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    log_file = log_folder / f"{timestamp}_create_project.log"
    
    base_path = Path(r"D:\AI-WORKS")
    project_folder = base_path / f"{project_number}-{project_name}"
    
    required_folders = ["source", "output", "backup", "logs", "src"]
    required_files = [
        "AI-WORKS_START.md",
        "AI-WORKS_MASTER.md",
        "AI-WORKS_HISTORY.md",
        "AI-WORKS_DECISIONS.md",
        "AI-WORKS_GLOSSARY.md",
        "AI-WORKS_GPT_START_PROMPT.md",
        "AI-WORKS_AI_REQUEST.md",
        "PROJECT_CONTEXT.md",
        "RULES.md",
        "README.md",
        "CHANGELOG.md",
        "TODO.md",
        "SESSION.md",
        "IDEA.md",
        "STATE.json",
        "config.json",
        "run.bat",
        "build_exe.bat",
        "REQUIREMENTS.md",
        "TECHNICAL_DECISIONS.md",
        "UI_FLOW.md",
        "ARCHITECTURE.md",
        "IMPLEMENTATION_PLAN.md",
        "DESIGN_FREEZE.md",
        "DOCUMENT_VALIDATION_RULES.md",
    ]
    
    with open(log_file, "w", encoding="utf-8") as f:
        f.write(f"실행 시간: {datetime.now().isoformat()}\n")
        f.write(f"프로젝트 번호: {project_number}\n")
        f.write(f"프로젝트 이름: {project_name}\n")
        f.write(f"생성 경로: {project_folder}\n")
        f.write(f"\n생성된 폴더 목록:\n")
        for folder in required_folders:
            f.write(f"- {folder}\n")
        f.write(f"\n복사된 파일 목록:\n")
        for file in required_files:
            f.write(f"- {file}\n")
        f.write(f"\n표준 버전: AI-WORKS Standard v2.0\n")
        f.write(f"템플릿 변수 치환: PROJECT_NAME={project_name}, PROJECT_NUMBER={project_number}\n")
        f.write(f"\nValidator 결과: {'통과' if status == 'success' else '실패'}\n")
        f.write(f"최종 상태: {status}\n")


def validate_project(project_number: str, project_name: str) -> bool:
    """프로젝트 생성 후 검증"""
    base_path = Path(r"D:\AI-WORKS")
    project_folder = base_path / f"{project_number}-{project_name}"
    
    print("\n" + "=" * 40)
    print("프로젝트 검증 시작")
    print("=" * 40)
    
    # 필수 폴더 검사
    print("\n폴더 검사")
    required_folders = ["source", "output", "backup", "logs", "src"]
    missing_folders = []
    for folder in required_folders:
        if (project_folder / folder).is_dir():
            print(f"[OK] {folder}")
        else:
            print(f"[FAIL] {folder}")
            missing_folders.append(folder)
    
    # 필수 파일 검사
    print("\n파일 검사")
    required_files = [
        "AI-WORKS_START.md",
        "AI-WORKS_MASTER.md",
        "AI-WORKS_HISTORY.md",
        "AI-WORKS_DECISIONS.md",
        "AI-WORKS_GLOSSARY.md",
        "AI-WORKS_GPT_START_PROMPT.md",
        "AI-WORKS_AI_REQUEST.md",
        "PROJECT_CONTEXT.md",
        "RULES.md",
        "README.md",
        "CHANGELOG.md",
        "TODO.md",
        "SESSION.md",
        "IDEA.md",
        "STATE.json",
        "config.json",
        "run.bat",
        "build_exe.bat",
        "REQUIREMENTS.md",
        "TECHNICAL_DECISIONS.md",
        "UI_FLOW.md",
        "ARCHITECTURE.md",
        "IMPLEMENTATION_PLAN.md",
        "DESIGN_FREEZE.md",
        "DOCUMENT_VALIDATION_RULES.md",
    ]
    missing_files = []
    for file in required_files:
        if (project_folder / file).is_file():
            print(f"[OK] {file}")
        else:
            print(f"[FAIL] {file}")
            missing_files.append(file)
    
    print("\n" + "=" * 40)
    
    if missing_folders or missing_files:
        print("검증 실패: 누락된 항목이 있습니다.")
        return False
    
    print("모든 검사 통과")
    print("프로젝트 생성 완료")
    print("=" * 40)
    return True


def can_approve_design_freeze(project_folder: Path) -> dict:
    """DESIGN_FREEZE 승인 가능 여부 검사"""
    design_docs = [
        "REQUIREMENTS.md",
        "TECHNICAL_DECISIONS.md",
        "UI_FLOW.md",
        "ARCHITECTURE.md",
        "IMPLEMENTATION_PLAN.md",
        "DESIGN_FREEZE.md",
        "DOCUMENT_VALIDATION_RULES.md",
    ]
    
    results = {
        "can_approve": True,
        "failed_docs": [],
        "details": []
    }
    
    for doc_name in design_docs:
        doc_path = project_folder / doc_name
        if not doc_path.exists():
            results["can_approve"] = False
            results["failed_docs"].append(doc_name)
            results["details"].append(f"[FAIL] {doc_name}: 파일 없음")
            continue
        
        content = doc_path.read_text(encoding="utf-8")
        doc_result = validate_document_content(content, doc_name)
        
        if not doc_result["valid"]:
            results["can_approve"] = False
            results["failed_docs"].append(doc_name)
        
        results["details"].extend(doc_result["details"])
    
    return results


def validate_document_content(content: str, doc_name: str) -> dict:
    """단일 문서 내용 검증 (DESIGN_FREEZE 조건용)"""
    result = {"valid": True, "details": []}
    
    placeholder_patterns = ["내용을 입력하세요", r"\bTODO\b", r"\bplaceholder\b", r"\bN/A\b"]
    for pattern in placeholder_patterns:
        if re.search(pattern, content):
            result["valid"] = False
            result["details"].append(f"[FAIL] {doc_name}: placeholder 발견 ('{pattern}')")
            return result
    
    min_length = 500 if doc_name != "DESIGN_FREEZE.md" and doc_name != "DOCUMENT_VALIDATION_RULES.md" else 100
    if len(content) < min_length:
        result["valid"] = False
        result["details"].append(f"[FAIL] {doc_name}: 길이 부족 ({len(content)}자, 최소 {min_length}자)")
        return result
    
    result["details"].append(f"[PASS] {doc_name}: 검증 통과")
    return result


def main() -> None:
    """메인 함수"""
    print("=" * 50)
    print("AI-WORKS 프로젝트 생성기 v2.0")
    print("AI-WORKS Standard v2.0 적용")
    print("=" * 50)
    
    # 템플릿 존재 여부 확인
    if not check_templates_exist():
        return
    
    project_number = get_project_number()
    project_name = get_project_name()
    
    if not confirm_creation(project_number, project_name):
        return
    
    if create_project_structure(project_number, project_name):
        if copy_templates(project_number, project_name):
            if validate_project(project_number, project_name):
                save_log(project_number, project_name, "success")
                print(f"\n프로젝트 생성 완료: AI-WORKS Standard v2.0")
            else:
                save_log(project_number, project_name, "failed")
                rollback_project(project_number, project_name)
        else:
            save_log(project_number, project_name, "failed")
            rollback_project(project_number, project_name)
    else:
        print("\n프로젝트 생성 실패!")


if __name__ == "__main__":
    main()


if __name__ == "__main__":
    main()