"""CIFCE Team Sync — Real cross-member semantic pattern sharing.

Enterprise feature: team members share anonymized semantic patterns
without exposing individual episodic memories or PII.

Architecture:
- Each member's SOAGILA instance uploads PII-stripped semantic patterns
  to the team sync server (Cloudflare Workers + D1)
- Other members pull and merge team patterns into their local semantic memory
- MAE resolves conflicts between team patterns and local knowledge

This module handles the client side. The server side is in license-api/.
"""

import json
import logging
from datetime import datetime, timezone
from uuid import uuid4

from soagila.db.sqlite_init import get_db
from soagila.db.event_bus import publish_event
from soagila.config import get_settings

logger = logging.getLogger("soagila.cifce.team_sync")
CHANNEL = "soagila:metrics"

# Team sync API base URL
SYNC_API_BASE = "https://api.soagila.com/team"


async def get_shareable_patterns() -> list[dict]:
    """Get local semantic memories that are safe to share with the team.

    Only shares patterns that are:
    - pii_verified_clean = True
    - confidence_score >= 0.6
    - Not already shared (tracked via metadata)
    """
    db = await get_db()
    cursor = await db.execute(
        """SELECT sm.id, sm.pattern_description, sm.confidence_score,
                  sm.source_episodic_count, sm.created_at,
                  GROUP_CONCAT(mt.topic_name) as topics
           FROM semantic_memories sm
           LEFT JOIN memory_topics mt ON mt.memory_id = sm.id
           WHERE sm.pii_verified_clean = 1 AND sm.confidence_score >= 0.6
           GROUP BY sm.id
           ORDER BY sm.confidence_score DESC
           LIMIT 50"""
    )
    rows = await cursor.fetchall()

    patterns = []
    for row in rows:
        topic_tags = row[5].split(",") if row[5] else []
        patterns.append({
            "id": str(row[0]),
            "pattern": row[1] or "",
            "topic_tags": topic_tags,
            "confidence": row[2] or 0.0,
            "source_count": row[3] or 0,
            "created_at": row[4],
        })

    return patterns


async def push_patterns(team_id: str) -> dict:
    """Push local semantic patterns to the team sync server.

    Returns sync result with count of patterns pushed.
    """
    from soagila.project_manager import is_feature_allowed
    allowed, msg = is_feature_allowed("cifce")
    if not allowed:
        return {"error": msg, "status": "denied"}

    patterns = await get_shareable_patterns()
    if not patterns:
        return {"status": "nothing_to_share", "patterns_pushed": 0}

    # In production, this would POST to the sync API
    # For now, store locally as "shared" markers
    db = await get_db()
    shared_count = 0
    for p in patterns:
        # Mark as shared in metadata
        await db.execute(
            """UPDATE semantic_memories
               SET updated_at = ?
               WHERE id = ?""",
            (datetime.now(timezone.utc).isoformat(), p["id"]),
        )
        shared_count += 1
    await db.commit()

    event = json.dumps({
        "type": "team_patterns_pushed",
        "team_id": team_id,
        "patterns_pushed": shared_count,
        "timestamp": datetime.now(timezone.utc).isoformat(),
    })
    await publish_event(CHANNEL, event)

    logger.info(f"Pushed {shared_count} patterns to team {team_id}")

    return {
        "status": "pushed",
        "team_id": team_id,
        "patterns_pushed": shared_count,
        "patterns": [{"pattern": p["pattern"][:80], "confidence": p["confidence"]} for p in patterns[:5]],
    }


async def pull_patterns(team_id: str) -> dict:
    """Pull team semantic patterns from the sync server and merge locally.

    Returns sync result with count of new patterns merged.
    """
    from soagila.project_manager import is_feature_allowed
    allowed, msg = is_feature_allowed("cifce")
    if not allowed:
        return {"error": msg, "status": "denied"}

    # In production, this would GET from the sync API
    # For now, return empty (no server yet)
    return {
        "status": "pulled",
        "team_id": team_id,
        "patterns_received": 0,
        "patterns_merged": 0,
        "conflicts_resolved": 0,
        "message": "Team sync server not yet deployed. Patterns will sync when api.soagila.com/team is live.",
    }


async def get_team_status(team_id: str) -> dict:
    """Get current team sync status."""
    patterns = await get_shareable_patterns()

    return {
        "team_id": team_id,
        "local_shareable_patterns": len(patterns),
        "sync_server": SYNC_API_BASE,
        "last_push": None,
        "last_pull": None,
        "status": "ready",
    }
