"""
Sophnet 日程提醒 HTTP API 服务。

启动（在 skills/sophnet-schedule/src 目录下）：
  uv run uvicorn server:app --host 0.0.0.0 --port 8765 --reload

认证：
  所有接口需要在 Header 中携带 X-API-Key（值来自 .env 中 API_KEY）。
  开发时可设置 API_KEY=dev 跳过认证（不建议生产使用）。

接口概览：
  GET  /health
  GET  /events?date=YYYY-MM-DD
  GET  /events?start=...&end=...
  POST /events
  DELETE /events/{event_id}
  GET  /events/conflicts?date=YYYY-MM-DD
  GET  /roc/events
  POST /roc/events
  PUT  /roc/events/{id}
  DELETE /roc/events/{id}
  GET  /roc/upcoming?days=30
  GET  /reminders?window=30
  GET  /tasks
  POST /tasks/trigger/daily-plan
  POST /tasks/sync
  GET  /daily-plan?date=YYYY-MM-DD
"""

from __future__ import annotations

import os
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional

import yaml
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse

# ── sys.path ──────────────────────────────────────────────────────────
sys.path.insert(0, str(Path(__file__).resolve().parent))

from config.settings import TIMEZONE, SKILL_BASE, TASK_REGISTRY_FILE
from gcal.client import CalendarAPIError, CalendarAuthError
from gcal.models import CalendarEvent
from services.calendar_backend import (
    active_provider,
    create_event as backend_create_event,
    delete_event as backend_delete_event,
    list_event_views,
    sync_local_events,
)
from services.conflict_detector import ConflictPair, detect_conflicts
from services.time_window import get_today_window
from services.datetime_utils import (
    DateTimeValidationError,
    build_event_range,
    current_date_str,
    current_year,
    local_date_label,
    local_date_window,
    now_local,
    parse_iso_datetime,
)
from services.job_store import append_job_if_absent, list_job_names
from services.google_integration import (
    complete_oauth_callback,
    get_guide_payload,
    get_last_sync_status,
    get_status_payload,
    start_oauth_session,
)
from services.runtime_utils import build_python_command
from apps.check_roc import build_year_events, upcoming_events, _load_config as _roc_config

from api.models import (
    ConflictOut, DailyPlanResponse, EventCreateRequest, EventCreateResponse,
    EventDeleteResponse, EventOut, EventsResponse, OkResponse,
    GoogleGuideResponse, GoogleStartRequest, GoogleStartResponse,
    GoogleStatusResponse, GoogleSyncResponse, GoogleSyncSummary,
    RemindersResponse, RocEventCreateRequest, RocEventOut, RocEventUpdateRequest,
    RocListResponse, RocUpcomingItem, RocUpcomingResponse,
    TaskItem, TasksResponse, TaskSyncResponse,
)

# ── 应用初始化 ────────────────────────────────────────────────────────

app = FastAPI(
    title="Sophnet 日程提醒 API",
    description="Google Calendar 日程调度 + ROC 周期事件 HTTP 接口",
    version="1.0.0",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],      # 生产环境请限定前端域名
    allow_methods=["*"],
    allow_headers=["*"],
)

_ROC_CONFIG_FILE = SKILL_BASE / "config" / "roc_events.yaml"
_API_KEY = os.environ.get("API_KEY", "dev")


# ── 认证 ──────────────────────────────────────────────────────────────

def _auth(x_api_key: Optional[str] = Header(None, alias="X-API-Key")) -> None:
    if x_api_key is None or (_API_KEY != "dev" and x_api_key != _API_KEY):
        raise HTTPException(status_code=401, detail="Invalid API key")


# ── 内部工具 ──────────────────────────────────────────────────────────

def _event_out(ev: CalendarEvent, provider: str = "", sync_state: str = "") -> EventOut:
    return EventOut(
        id=ev.id,
        summary=ev.summary,
        start=ev.start.isoformat(),
        end=ev.end.isoformat(),
        is_all_day=ev.is_all_day,
        location=ev.location,
        description=ev.description,
        status=ev.status,
        duration_minutes=ev.duration_minutes(),
        provider=provider,
        sync_state=sync_state,
    )


def _conflict_out(cp: ConflictPair) -> ConflictOut:
    ta = f"{cp.a.start.strftime('%H:%M')}–{cp.a.end.strftime('%H:%M')}"
    tb = f"{cp.b.start.strftime('%H:%M')}–{cp.b.end.strftime('%H:%M')}"
    gap = int((cp.b.start - cp.a.end).total_seconds() / 60) if cp.is_tight else 0
    return ConflictOut(
        type="tight" if cp.is_tight else "conflict",
        event_a=cp.a.summary,
        event_b=cp.b.summary,
        time_a=ta,
        time_b=tb,
        overlap_minutes=cp.overlap_minutes,
        gap_minutes=gap,
        text=cp.format_text(),
    )


def _parse_date_window(date: str) -> tuple[datetime, datetime]:
    """将 YYYY-MM-DD 转为业务时区当日区间。"""
    try:
        return local_date_window(date, TIMEZONE)
    except DateTimeValidationError as e:
        raise HTTPException(400, str(e))


def _read_roc_yaml() -> dict:
    with open(_ROC_CONFIG_FILE, encoding="utf-8") as f:
        return yaml.safe_load(f)


def _write_roc_yaml(data: dict) -> None:
    with open(_ROC_CONFIG_FILE, "w", encoding="utf-8") as f:
        yaml.dump(data, f, allow_unicode=True, sort_keys=False)


def _callback_url(request: Request) -> str:
    return str(request.base_url).rstrip("/") + "/integrations/google/callback"


def _callback_html(ok: bool, message: str) -> HTMLResponse:
    title = "授权成功" if ok else "授权失败"
    color = "#1b7f3b" if ok else "#b42318"
    body = (
        "<!doctype html><html><head><meta charset='utf-8'>"
        f"<title>{title}</title></head>"
        "<body style='font-family:sans-serif;padding:32px'>"
        f"<h2 style='color:{color}'>{title}</h2>"
        f"<p>{message}</p>"
        "<p>现在可以关闭这个窗口。</p>"
        "</body></html>"
    )
    return HTMLResponse(body, status_code=200 if ok else 400)


# ── 健康检查 ──────────────────────────────────────────────────────────

@app.get("/health", tags=["系统"])
def health() -> dict:
    return {"ok": True, "service": "sophnet-schedule", "version": "1.0.0"}


# ── 日历事件 ──────────────────────────────────────────────────────────

@app.get("/events", response_model=EventsResponse, tags=["日历"])
def list_events(
    date: Optional[str] = Query(None, description="YYYY-MM-DD，查询当日"),
    start: Optional[str] = Query(None, description="ISO 8601 开始时间"),
    end: Optional[str]   = Query(None, description="ISO 8601 结束时间"),
    _: None = Depends(_auth),
) -> EventsResponse:
    if date:
        t_start, t_end = _parse_date_window(date)
        label = date
    elif start and end:
        try:
            t_start = parse_iso_datetime(start, TIMEZONE)
            t_end   = parse_iso_datetime(end, TIMEZONE)
        except DateTimeValidationError as e:
            raise HTTPException(400, str(e))
        if t_end <= t_start:
            raise HTTPException(400, "end 必须晚于 start")
        label = local_date_label(t_start, TIMEZONE)
    else:
        t_start, t_end = get_today_window(TIMEZONE)
        label = current_date_str(TIMEZONE)

    try:
        views = list_event_views(t_start, t_end)
    except (CalendarAuthError, CalendarAPIError) as e:
        raise HTTPException(502, str(e))

    events = [item.event for item in views]
    conflicts = detect_conflicts(events)
    provider = active_provider()
    return EventsResponse(
        date=label,
        events=[_event_out(item.event, provider=item.provider, sync_state=item.sync_state) for item in views],
        conflicts=[_conflict_out(c) for c in conflicts],
        provider=provider,
        active_mode=provider,
    )


@app.post("/events", response_model=EventCreateResponse, tags=["日历"])
def create_event(
    body: EventCreateRequest,
    _: None = Depends(_auth),
) -> EventCreateResponse:
    try:
        start_dt, end_dt = build_event_range(
            body.date,
            body.start,
            body.end,
            body.duration,
            TIMEZONE,
        )
    except DateTimeValidationError as e:
        raise HTTPException(400, str(e))

    try:
        created = backend_create_event(
            summary=body.summary,
            start=start_dt,
            end=end_dt,
            location=body.location,
            description=body.description,
            remind_minutes=body.remind,
        )
    except (CalendarAuthError, CalendarAPIError) as e:
        return EventCreateResponse(ok=False, error=str(e), provider=active_provider())

    reminder_registered = False
    if body.remind > 0 and created.event_id:
        try:
            _register_one_off_reminder(body, start_dt, created.event_id)
            reminder_registered = True
        except Exception:
            pass  # 提醒注册失败不影响事件创建结果

    return EventCreateResponse(
        ok=True,
        event_id=created.event_id,
        summary=body.summary,
        start=start_dt.isoformat(),
        end=end_dt.isoformat(),
        reminder_registered=reminder_registered,
        provider=created.provider,
        sync_state=created.sync_state,
    )


@app.delete("/events/{event_id}", response_model=EventDeleteResponse, tags=["日历"])
def delete_event(
    event_id: str,
    _: None = Depends(_auth),
) -> EventDeleteResponse:
    try:
        deleted = backend_delete_event(event_id)
        if not deleted:
            return EventDeleteResponse(ok=False, event_id=event_id, error="事件不存在")
        return EventDeleteResponse(ok=True, event_id=event_id)
    except (CalendarAuthError, CalendarAPIError) as e:
        return EventDeleteResponse(ok=False, event_id=event_id, error=str(e))


@app.get("/events/conflicts", response_model=EventsResponse, tags=["日历"])
def get_conflicts(
    date: Optional[str] = Query(None, description="YYYY-MM-DD，默认今日"),
    _: None = Depends(_auth),
) -> EventsResponse:
    return list_events(date=date, start=None, end=None, _=_)


# ── ROC 周期事件 ──────────────────────────────────────────────────────

@app.get("/roc/events", response_model=RocListResponse, tags=["ROC"])
def roc_list(
    year: Optional[int] = Query(None, description="年份，默认今年"),
    _: None = Depends(_auth),
) -> RocListResponse:
    y = year or current_year(TIMEZONE)
    cfg = _read_roc_yaml()
    year_events = build_year_events(y, cfg)

    ev_map = {e["id"]: e for e in year_events}
    result = []
    for raw in cfg.get("events", []):
        ye = ev_map.get(raw["id"], {})
        result.append(RocEventOut(
            id=raw["id"],
            name=raw["name"],
            rule=raw["rule"],
            reminder_time=raw.get("reminder_time", "09:00"),
            lead_days=int(raw.get("lead_days", 0)),
            description=raw.get("description", ""),
            event_date=ye.get("event_date"),
            reminder_date=ye.get("reminder_date"),
        ))
    return RocListResponse(year=y, events=result)


@app.post("/roc/events", response_model=OkResponse, tags=["ROC"])
def roc_create(
    body: RocEventCreateRequest,
    _: None = Depends(_auth),
) -> OkResponse:
    cfg = _read_roc_yaml()
    events: list = cfg.get("events", [])
    if any(e["id"] == body.id for e in events):
        raise HTTPException(409, f"ROC 事件 ID 已存在：{body.id}")
    events.append({
        "id": body.id,
        "name": body.name,
        "rule": body.rule,
        "reminder_time": body.reminder_time,
        "lead_days": body.lead_days,
        "description": body.description,
    })
    cfg["events"] = events
    _write_roc_yaml(cfg)
    return OkResponse(id=body.id, message=f"已添加 ROC 事件：{body.name}")


@app.put("/roc/events/{roc_id}", response_model=OkResponse, tags=["ROC"])
def roc_update(
    roc_id: str,
    body: RocEventUpdateRequest,
    _: None = Depends(_auth),
) -> OkResponse:
    cfg = _read_roc_yaml()
    events: list = cfg.get("events", [])
    for ev in events:
        if ev["id"] == roc_id:
            if body.name is not None:          ev["name"] = body.name
            if body.rule is not None:          ev["rule"] = body.rule
            if body.reminder_time is not None: ev["reminder_time"] = body.reminder_time
            if body.lead_days is not None:     ev["lead_days"] = body.lead_days
            if body.description is not None:   ev["description"] = body.description
            cfg["events"] = events
            _write_roc_yaml(cfg)
            return OkResponse(message=f"已更新 ROC 事件：{roc_id}")
    raise HTTPException(404, f"ROC 事件不存在：{roc_id}")


@app.delete("/roc/events/{roc_id}", response_model=OkResponse, tags=["ROC"])
def roc_delete(
    roc_id: str,
    _: None = Depends(_auth),
) -> OkResponse:
    cfg = _read_roc_yaml()
    events: list = cfg.get("events", [])
    new_events = [e for e in events if e["id"] != roc_id]
    if len(new_events) == len(events):
        raise HTTPException(404, f"ROC 事件不存在：{roc_id}")
    cfg["events"] = new_events
    _write_roc_yaml(cfg)
    return OkResponse(message=f"已删除 ROC 事件：{roc_id}")


@app.get("/roc/upcoming", response_model=RocUpcomingResponse, tags=["ROC"])
def roc_upcoming(
    days: int = Query(30, description="查询未来 N 天"),
    _: None = Depends(_auth),
) -> RocUpcomingResponse:
    today = current_date_str(TIMEZONE)
    year  = int(today[:4])
    cfg = _read_roc_yaml()
    year_events = build_year_events(year, cfg)
    ups = upcoming_events(year_events, today, days)
    return RocUpcomingResponse(
        today=today,
        days=days,
        upcoming=[RocUpcomingItem(**{
            "id":                   u["id"],
            "name":                 u["name"],
            "event_date":           u["event_date"],
            "reminder_date":        u["reminder_date"],
            "days_until_reminder":  u["days_until_reminder"],
            "days_until_event":     u["days_until_event"],
            "description":          u.get("description", ""),
        }) for u in ups],
    )


# ── 提醒 ──────────────────────────────────────────────────────────────

@app.get("/reminders", response_model=RemindersResponse, tags=["提醒"])
def get_reminders(
    window: int = Query(30, description="时间窗口（分钟），默认 30"),
    _: None = Depends(_auth),
) -> RemindersResponse:
    result = subprocess.run(
        build_python_command(SKILL_BASE / "apps" / "check_reminders.py", "--window", str(window), "--json"),
        capture_output=True, text=True, cwd=str(SKILL_BASE),
    )
    if result.returncode != 0:
        detail = result.stderr.strip() or result.stdout.strip() or "检查提醒失败"
        raise HTTPException(502, detail[:300])

    import json as _json
    try:
        data = _json.loads(result.stdout)
    except Exception as e:
        raise HTTPException(502, f"提醒结果解析失败：{e}")

    if not data.get("ok", True):
        raise HTTPException(502, data.get("error", "提醒检查失败"))

    provider = active_provider()
    return RemindersResponse(
        window_minutes=window,
        reminders=data.get("reminders", []),
        provider=provider,
        active_mode=provider,
    )


# ── Cron 任务 ─────────────────────────────────────────────────────────

@app.get("/tasks", response_model=TasksResponse, tags=["任务"])
def list_tasks(_: None = Depends(_auth)) -> TasksResponse:
    with open(TASK_REGISTRY_FILE, encoding="utf-8") as f:
        cfg = yaml.safe_load(f)
    tasks = []
    for t in cfg.get("tasks", []):
        sch = t.get("schedule", {})
        tasks.append(TaskItem(
            name=t["name"],
            description=t.get("description", ""),
            schedule_kind=sch.get("kind", ""),
            schedule_expr=sch.get("time") or sch.get("expr") or "",
            type=t.get("type", ""),
        ))
    return TasksResponse(tasks=tasks)


@app.post("/tasks/trigger/daily-plan", response_model=OkResponse, tags=["任务"])
def trigger_daily_plan(
    dry_run: bool = Query(False),
    _: None = Depends(_auth),
) -> OkResponse:
    cmd = build_python_command(SKILL_BASE / "apps" / "generate_daily_plan.py")
    if dry_run:
        cmd.append("--dry-run")
    result = subprocess.run(cmd, capture_output=True, text=True, cwd=str(SKILL_BASE))
    if result.returncode != 0:
        raise HTTPException(500, f"生成失败：{result.stderr[:200]}")
    return OkResponse(message="今日计划已生成" + ("（dry-run）" if dry_run else "，提醒已注册"))


@app.post("/tasks/sync", response_model=TaskSyncResponse, tags=["任务"])
def sync_tasks(
    dry_run: bool = Query(False),
    _: None = Depends(_auth),
) -> TaskSyncResponse:
    """
    重读 task_registry.yaml 并立即同步到 jobs.json。

    - 已存在同名任务：跳过（不覆盖）
    - 新任务：写入 jobs.json，当天生效
    - dry_run=true：只计算差异，不写入
    """
    import json as _json
    from apps.register_tasks import load_fixed_tasks, build_cron_job_from_task

    today = now_local(TIMEZONE)

    try:
        tasks = load_fixed_tasks(provider=active_provider())
    except Exception as e:
        raise HTTPException(500, f"读取 task_registry.yaml 失败：{e}")

    try:
        existing = list_job_names()
    except Exception as e:
        raise HTTPException(500, f"读取 jobs.json 失败：{e}")
    added: list = []
    skipped: list = []
    errors: list = []

    for task in tasks:
        name = task.get("name", "未命名")
        try:
            payload = build_cron_job_from_task(task, today)
            if payload is None:
                errors.append(f"{name}：配置不完整，跳过")
                continue
            if dry_run and name in existing:
                skipped.append(name)
                continue
            if dry_run:
                existing.add(name)
                added.append(name)
                continue
            if append_job_if_absent(payload):
                existing.add(name)
                added.append(name)
            else:
                skipped.append(name)
        except Exception as e:
            errors.append(f"{name}：{e}")

    suffix = "（dry-run，未写入）" if dry_run else ""
    return TaskSyncResponse(
        ok=True,
        dry_run=dry_run,
        added=added,
        skipped=skipped,
        errors=errors,
        message=f"同步完成{suffix}：新增 {len(added)} 个，跳过 {len(skipped)} 个，失败 {len(errors)} 个",
    )


# ── 日报 ──────────────────────────────────────────────────────────────

@app.get("/daily-plan", response_model=DailyPlanResponse, tags=["日报"])
def get_daily_plan(
    date: Optional[str] = Query(None, description="YYYY-MM-DD，默认今日"),
    _: None = Depends(_auth),
) -> DailyPlanResponse:
    label = date or current_date_str(TIMEZONE)
    t_start, t_end = _parse_date_window(label)

    try:
        views = list_event_views(t_start, t_end)
    except (CalendarAuthError, CalendarAPIError) as e:
        raise HTTPException(502, str(e))

    events = [item.event for item in views]
    conflicts = detect_conflicts(events)

    # 尝试读取已生成的日报 Markdown
    md_path = SKILL_BASE / "daily" / f"cron-{label.replace('-', '')}.md"
    markdown = md_path.read_text(encoding="utf-8") if md_path.exists() else ""

    return DailyPlanResponse(
        date=label,
        events=[_event_out(item.event, provider=item.provider, sync_state=item.sync_state) for item in views],
        conflicts=[_conflict_out(c) for c in conflicts],
        reminders_registered=0,  # 只读接口，不注册
        markdown=markdown,
        provider=active_provider(),
    )


# ── Google 接入 ──────────────────────────────────────────────────────

@app.get("/integrations/google/status", response_model=GoogleStatusResponse, tags=["集成"])
def google_status(_: None = Depends(_auth)) -> GoogleStatusResponse:
    return GoogleStatusResponse(**get_status_payload())


@app.get("/integrations/google/guide", response_model=GoogleGuideResponse, tags=["集成"])
def google_guide(
    request: Request,
    _: None = Depends(_auth),
) -> GoogleGuideResponse:
    return GoogleGuideResponse(**get_guide_payload(_callback_url(request)))


@app.post("/integrations/google/start", response_model=GoogleStartResponse, tags=["集成"])
def google_start(
    body: GoogleStartRequest,
    request: Request,
    _: None = Depends(_auth),
) -> GoogleStartResponse:
    result = start_oauth_session(
        client_id=body.client_id,
        client_secret=body.client_secret,
        redirect_uri=_callback_url(request),
    )
    return GoogleStartResponse(**result)


@app.get("/integrations/google/callback", response_class=HTMLResponse, tags=["集成"])
def google_callback(
    state: str,
    code: Optional[str] = Query(None),
    error: Optional[str] = Query(None),
    error_description: Optional[str] = Query(None),
) -> HTMLResponse:
    try:
        complete_oauth_callback(state, code, error, error_description)
        return _callback_html(True, "Google 授权成功，已保存凭据，下一步可执行首次同步。")
    except CalendarAuthError as e:
        return _callback_html(False, str(e))


@app.post("/integrations/google/sync", response_model=GoogleSyncResponse, tags=["集成"])
def google_sync(_: None = Depends(_auth)) -> GoogleSyncResponse:
    try:
        summary = sync_local_events()
    except (CalendarAuthError, CalendarAPIError) as e:
        raise HTTPException(502, str(e))

    status = get_status_payload()
    return GoogleSyncResponse(
        active_mode=status["active_mode"],
        google_state=status["google_state"],
        summary=GoogleSyncSummary(**summary),
    )


@app.get("/integrations/google/sync-status", response_model=GoogleSyncSummary, tags=["集成"])
def google_sync_status(_: None = Depends(_auth)) -> GoogleSyncSummary:
    return GoogleSyncSummary(**get_last_sync_status())


# ── 内部：提醒注册 ────────────────────────────────────────────────────

def _register_one_off_reminder(
    body: EventCreateRequest,
    start_dt: datetime,
    event_id: str,
) -> None:
    """直接用 task_builder 注册提醒 cron job，不再调用 add_event.py（避免重复创建事件）。"""
    from datetime import timezone as _tz
    from services.task_builder import build_reminder_task, build_reminder_task_name
    from compat import make_aware

    start_aware = make_aware(start_dt, TIMEZONE)
    remind_at_utc = (start_aware - timedelta(minutes=body.remind)).astimezone(_tz.utc)
    name = build_reminder_task_name(body.summary, start_aware, event_id)
    payload = build_reminder_task(
        name=name,
        remind_at_utc=remind_at_utc,
        message=(
            f"⏰ **{body.summary}** 将在 {body.remind} 分钟后开始\n"
            f"🕐 {start_dt.strftime('%H:%M')}"
            + (f"  📍 {body.location}" if body.location else "")
        ),
    )

    try:
        append_job_if_absent(payload)
    except Exception:
        pass  # jobs.json 不存在时静默忽略
