File size: 9,704 Bytes
96b1f03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
"""Singularity task-tracker API integration."""

import asyncio
import logging
import re
from datetime import datetime, timedelta, timezone

import httpx

from app.config import get_settings
from app.models.checklist import ProjectPlan

logger = logging.getLogger(__name__)

SINGULARITY_BASE = "https://api.singularity-app.com/v2"
TZ_OFFSET = timezone(timedelta(hours=5))  # UTC+5


def _parse_date(date_str: str) -> datetime | None:
    """Try to parse a date string in various formats.

    Supported: '19 апреля 2026', '19.04.2026', '2026-04-19',
    'Понедельник, 19 апреля 2026', 'Понедельник, 2026-04-19'.
    """
    months_ru = {
        "января": 1, "февраля": 2, "марта": 3, "апреля": 4,
        "мая": 5, "июня": 6, "июля": 7, "августа": 8,
        "сентября": 9, "октября": 10, "ноября": 11, "декабря": 12,
    }
    s = date_str.strip()
    # Strip weekday prefix: "Понедельник, 19 апреля 2026" -> "19 апреля 2026"
    s = re.sub(r"^[А-Яа-яёЁ]+,\s*", "", s)
    # Strip trailing "г." or "года"
    s = re.sub(r"\s*г\.?\s*$", "", s)
    s = re.sub(r"\s*года\s*$", "", s)
    current_year = datetime.now().year
    # ISO format: "2026-04-19" or "2026-03-11"
    m = re.search(r"(\d{4})-(\d{2})-(\d{2})", s)
    if m:
        return datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)), tzinfo=TZ_OFFSET)
    # "19 апреля 2026"
    m = re.search(r"(\d{1,2})\s+(\S+)\s+(\d{4})", s)
    if m:
        day, month_name, year = int(m.group(1)), m.group(2).lower(), int(m.group(3))
        month = months_ru.get(month_name)
        if month:
            return datetime(year, month, day, tzinfo=TZ_OFFSET)
    # "19 апреля" (no year — assume current year)
    m = re.search(r"(\d{1,2})\s+(\S+)", s)
    if m:
        day, month_name = int(m.group(1)), m.group(2).lower().rstrip(",.")
        month = months_ru.get(month_name)
        if month:
            return datetime(current_year, month, day, tzinfo=TZ_OFFSET)
    # "19.04.2026"
    m = re.search(r"(\d{1,2})\.(\d{1,2})\.(\d{4})", s)
    if m:
        return datetime(int(m.group(3)), int(m.group(2)), int(m.group(1)), tzinfo=TZ_OFFSET)
    # "19.04" (no year)
    m = re.search(r"(\d{1,2})\.(\d{1,2})$", s)
    if m:
        return datetime(current_year, int(m.group(2)), int(m.group(1)), tzinfo=TZ_OFFSET)
    return None


def _parse_period_dates(period: str) -> tuple[datetime | None, datetime | None]:
    """Parse phase period like '14 апреля – 20 апреля 2026' or '2026-03-11 — 2026-04-14'."""
    # Split on en-dash/em-dash surrounded by spaces (not bare hyphens, to avoid splitting ISO dates)
    parts = re.split(r"\s+[–—]\s+", period)
    if len(parts) != 2:
        # Fallback: split on " - " (hyphen with spaces)
        parts = re.split(r"\s+-\s+", period)
    if len(parts) == 2:
        end_dt = _parse_date(parts[1])
        start_dt = _parse_date(parts[0])
        # If start has no year, borrow from end
        if start_dt is None and end_dt is not None:
            start_dt = _parse_date(parts[0].strip() + f" {end_dt.year}")
        return start_dt, end_dt
    return None, None


def _parse_time_range(time_str: str, date_str: str) -> tuple[str, int] | None:
    """Parse '11:04–12:34' + date into (ISO start in UTC, timeLength in minutes).

    Returns None if parsing fails.
    """
    m = re.match(r"(\d{1,2}):(\d{2})\s*[–—-]\s*(\d{1,2}):(\d{2})", time_str.strip())
    if not m:
        return None
    h1, m1, h2, m2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))

    base_date = _parse_date(date_str)
    if base_date is None:
        return None

    start_local = base_date.replace(hour=h1, minute=m1, second=0, microsecond=0)
    start_utc = start_local.astimezone(timezone.utc)

    duration = (h2 * 60 + m2) - (h1 * 60 + m1)
    if duration <= 0:
        duration += 24 * 60  # overnight task

    return start_utc.strftime("%Y-%m-%dT%H:%M:%S.000Z"), duration


def _headers() -> dict[str, str]:
    settings = get_settings()
    return {
        "Authorization": f"Bearer {settings.singularity_api_key}",
        "Content-Type": "application/json",
    }


async def export_plan_to_singularity(plan: ProjectPlan) -> dict:
    """Create project, sub-projects (phases), and tasks in Singularity.

    Returns dict with created project id and stats.
    """
    # Debug: dump plan
    import json as _json
    logger.info("PLAN DUMP: %s", _json.dumps(plan.model_dump(), ensure_ascii=False, default=str)[:2000])
    headers = _headers()

    async with httpx.AsyncClient(timeout=30) as client:
        # 1. Create root project
        project_body = {"title": plan.project_name}
        # Try to get overall date range from phases
        all_starts: list[datetime] = []
        all_ends: list[datetime] = []
        for phase in plan.phases:
            s, e = _parse_period_dates(phase.period)
            if s:
                all_starts.append(s)
            if e:
                all_ends.append(e)
        if all_starts:
            project_body["start"] = min(all_starts).astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
        if all_ends:
            project_body["end"] = max(all_ends).astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")

        resp = await client.post(f"{SINGULARITY_BASE}/project", json=project_body, headers=headers)
        if resp.status_code >= 400:
            logger.error("Root project creation failed: %s\nRequest: %s\nResponse: %s",
                         resp.status_code, project_body, resp.text[:500])
        resp.raise_for_status()
        root_project = resp.json()
        root_id = root_project["project"]["id"]
        logger.info("Created Singularity project %s: %s", root_id, plan.project_name)

        tasks_created = 0

        # 2. Create sub-projects for each phase
        for phase_idx, phase in enumerate(plan.phases):
            phase_body: dict = {
                "title": phase.title,
                "parent": root_id,
                "parentOrder": phase_idx,
            }
            # Phase note = goals description
            if phase.goals:
                goals_text = "\n".join(f"• {g.text} (дедлайн: {g.deadline}, приоритет: {g.priority})" for g in phase.goals)
                phase_body["note"] = goals_text

            s, e = _parse_period_dates(phase.period)
            if s:
                phase_body["start"] = s.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
            if e:
                phase_body["end"] = e.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")

            resp = await client.post(f"{SINGULARITY_BASE}/project", json=phase_body, headers=headers)
            if resp.status_code >= 400:
                logger.error("Phase project creation failed: %s\nRequest: %s\nResponse: %s",
                             resp.status_code, phase_body, resp.text[:500])
                continue  # skip this phase
            phase_project = resp.json()
            phase_id = phase_project["project"]["id"]
            logger.info("Created phase sub-project %s: %s", phase_id, phase.title)

            # 3. Create tasks for each time slot in each week/day
            task_order = 0
            for week in phase.weeks:
                for day in week.days:
                    for slot in day.slots:
                        task_body: dict = {
                            "title": slot.task[:255],
                            "projectId": phase_id,
                            "scheduleOrder": task_order,
                        }

                        parsed = _parse_time_range(slot.time, day.date)
                        if parsed:
                            start_utc, duration = parsed
                            task_body["start"] = start_utc
                            task_body["timeLength"] = duration
                            task_body["useTime"] = True
                        else:
                            # Fallback: set date without time
                            day_dt = _parse_date(day.date)
                            if day_dt:
                                task_body["start"] = day_dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")

                        # Rate-limit: pause between requests to avoid 429
                        for attempt in range(3):
                            resp = await client.post(f"{SINGULARITY_BASE}/task", json=task_body, headers=headers)
                            if resp.status_code == 429:
                                wait = 2 ** attempt  # 1s, 2s, 4s
                                logger.warning("Rate limited (429), retrying in %ds...", wait)
                                await asyncio.sleep(wait)
                                continue
                            break
                        if resp.status_code >= 400:
                            logger.error("Task creation failed: %s %s\nRequest: %s\nResponse: %s",
                                         resp.status_code, resp.reason_phrase, task_body, resp.text[:500])
                            task_order += 1
                            continue  # skip failed task, don't crash
                        task_order += 1
                        tasks_created += 1
                        await asyncio.sleep(0.15)  # throttle to stay under rate limit

        logger.info("Export complete: %d tasks created", tasks_created)
        return {
            "project_id": root_id,
            "phases_created": len(plan.phases),
            "tasks_created": tasks_created,
        }