File size: 3,900 Bytes
0b2210a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import json
import os
from pathlib import Path
import logging

logger = logging.getLogger(__name__)

class ProjectContext:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not hasattr(self, '_initialized'):
            self._initialized = False
            self.project_path = None
            self.project_id = None
            # Корень папки AIColab (на уровень выше от core/) - нормализуем регистр
            self.base_dir = Path(__file__).resolve().parent.parent
            # Принудительная нормализация к нижнему регистру для Windows
            if os.name == 'nt':
                self.base_dir = Path(str(self.base_dir).lower())
    
    async def ensure_initialized(self):
        """Ленивая инициализация"""
        if not self._initialized:
            # Всегда смотрим в папку projects в корне AIColab
            projects_dir = self.base_dir / "projects"
            if projects_dir.exists():
                # Находим последний измененный проект
                try:
                    projects = sorted(
                        [p for p in projects_dir.iterdir() if p.is_dir()],
                        key=lambda p: p.stat().st_mtime,
                        reverse=True
                    )
                    if projects:
                        self.project_path = projects[0]
                        self.project_id = projects[0].name
                except Exception as e:
                    logger.warning(f"Ошибка при поиске проектов в {projects_dir}: {e}")
            
            self._initialized = True
    
    def get_current_project_path(self):
        """Получить путь к текущему проекту"""
        if self.project_path and self.project_path.exists():
            return self.project_path
        
        # Fallback: поиск в корне AIColab
        projects_dir = self.base_dir / "projects"
        if projects_dir.exists():
            try:
                projects = sorted(
                    [p for p in projects_dir.iterdir() if p.is_dir()],
                    key=lambda p: p.stat().st_mtime,
                    reverse=True
                )
                if projects:
                    self.project_path = projects[0]
                    self.project_id = projects[0].name
                    return projects[0]
            except Exception as e:
                logger.warning(f"Ошибка поиска проекта: {e}")
        
        # Дефолтный проект внутри корня AIColab
        default_project = projects_dir / "default"
        default_project.mkdir(parents=True, exist_ok=True)
        self.project_path = default_project
        self.project_id = "default"
        return default_project

    def get_role_log_path(self, role: str, log_type: str, filename: str) -> Path:
        """Получить путь к логу конкретной роли."""
        project_path = self.get_current_project_path()
        # logs/subjects/{role}/{log_type}/{filename}
        log_dir = project_path / "logs" / "subjects" / role / log_type
        log_dir.mkdir(parents=True, exist_ok=True)
        return log_dir / filename
    
    def get_state(self):
        return {
            'state': 'initialized' if self._initialized else 'uninitialized',
            'project_id': self.project_id,
            'project_path': str(self.project_path) if self.project_path else None
        }
    
    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance