import requests
import json

MONDAY_TOKEN = "REMOVED"
MONDAY_URL = "https://api.monday.com/v2"

OP_URL = "https://projetos.rede5.com.br"
OP_API_KEY = "9c704b1c48939f97463fd9d811a9de050317b85224b93694d6e037f0799d37c2"
OP_AUTH = ('apikey', OP_API_KEY)

def monday_query(query):
    headers = {"Authorization": MONDAY_TOKEN, "Content-Type": "application/json"}
    resp = requests.post(MONDAY_URL, json={'query': query}, headers=headers)
    return resp.json()

def run_sync_v4():
    print("--- Publicando Tarefas (Sincronização Robusta V4) ---")
    
    # 1. Obter mapeamento de usuários OP
    op_users = requests.get(f"{OP_URL}/api/v3/users", auth=OP_AUTH).json()
    user_mapping = {u['name']: u['id'] for u in op_users['_embedded']['elements']}
    
    # 2. Mapear Projetos Reais no OP
    op_projects = requests.get(f"{OP_URL}/api/v3/projects", auth=OP_AUTH).json()
    project_mapping = {p['name']: p['id'] for p in op_projects['_embedded']['elements']}
    
    # 3. Mapeamento de Sprints do Monday
    sprints_data = monday_query("{ boards(ids: 18400111743) { items_page { items { id name } } } }")
    monday_id_to_name = {str(item['id']): item['name'] for item in sprints_data['data']['boards'][0]['items_page']['items']}

    # 4. Buscar Tasks no Monday com query detalhada para relações
    query = """
    {
      boards(ids: 18400111746) {
        items_page {
          items {
            id
            name
            column_values {
              id
              text
              type
              value
              ... on BoardRelationValue {
                linked_item_ids
              }
            }
          }
        }
      }
    }
    """
    data = monday_query(query)
    tasks = data['data']['boards'][0]['items_page']['items']
    print(f"Processando {len(tasks)} tarefas...")

    for task in tasks:
        target_project_name = None
        owner_name = None
        doc_link = None
        description_lines = []

        for cv in task['column_values']:
            # Identificar Projeto via linked_item_ids
            if cv['id'] == "task_sprint" and cv.get('linked_item_ids'):
                lid = str(cv['linked_item_ids'][0])
                if lid in monday_id_to_name:
                    target_project_name = monday_id_to_name[lid]
            
            if cv['id'] == "task_owner":
                owner_name = cv['text']

            # Link do Doc
            if cv['id'] == "monday_doc_v2" and cv['value']:
                try:
                    val = json.loads(cv['value'])
                    if 'files' in val and val['files']:
                        doc_link = val['files'][0].get('linkToFile')
                except: pass

            # Dados Extras para Descrição
            if cv['text'] and cv['type'] not in ["people", "board_relation", "direct_doc"]:
                description_lines.append(f"**{cv['id'].replace('task_', '').capitalize()}**: {cv['text']}")

        if target_project_name and target_project_name in project_mapping:
            p_id = project_mapping[target_project_name]
            owner_id = user_mapping.get(owner_name)

            final_desc = ""
            if doc_link:
                final_desc += f"### [📄 VER DESCRIÇÃO COMPLETA NO MONDAY]({doc_link})\n\n---\n"
            final_desc += "\n".join(description_lines)

            wp_payload = {
                "subject": task['name'],
                "description": {"format": "markdown", "raw": final_desc},
                "_links": {
                    "project": {"href": f"/api/v3/projects/{p_id}"}
                }
            }
            if owner_id:
                wp_payload["_links"]["assignee"] = {"href": f"/api/v3/users/{owner_id}"}

            print(f"Publicando: {task['name']} -> {target_project_name} (Responsável: {owner_name or 'Nenhum'})")
            requests.post(f"{OP_URL}/api/v3/work_packages", auth=OP_AUTH, json=wp_payload)

if __name__ == "__main__":
    run_sync_v4()
