import os
import csv
import json


class DataManager:
    def __init__(self, base_projects_dir="projects"):
        self.base_projects_dir = base_projects_dir
        if not os.path.exists(self.base_projects_dir):
            os.makedirs(self.base_projects_dir)

    def create_project_folder(self, project_name):
        """ایجاد پوشه اصلی پروژه"""
        project_path = os.path.join(self.base_projects_dir, project_name)
        if not os.path.exists(project_path):
            os.makedirs(project_path)
        return project_path

    def save_tree_data(self, project_path, tree_data_list):
        """ذخیره اطلاعات کل درخت در tree_data.csv"""
        file_path = os.path.join(project_path, "tree_data.csv")
        headers = ["level", "segment_id", "parent_segment_id", "original_sentences", "semantic_unit"]

        with open(file_path, mode='w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=headers)
            writer.writeheader()
            for row in tree_data_list:
                # تبدیل لیست جملات به رشته JSON برای ذخیره امن در CSV
                row_copy = row.copy()
                if isinstance(row_copy.get("original_sentences"), list):
                    row_copy["original_sentences"] = json.dumps(row_copy["original_sentences"], ensure_ascii=False)
                writer.writerow(row_copy)

    def save_graph_data(self, project_path, node_id, propositions, relations, scores):
        """ذخیره ۳ فایل CSV مربوط به گراف یک نود خاص"""
        graph_dir = os.path.join(project_path, f"{node_id}_graph")
        if not os.path.exists(graph_dir):
            os.makedirs(graph_dir)

        # 1. save propositions.csv
        with open(os.path.join(graph_dir, "propositions.csv"), mode='w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=["proposition_id", "sentence", "proposition_text"])
            writer.writeheader()
            writer.writerows(propositions)

        # 2. save relations.csv
        with open(os.path.join(graph_dir, "relations.csv"), mode='w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=["relation_id", "source_proposition_id", "target_proposition_id",
                                                   "relation_type"])
            writer.writeheader()
            writer.writerows(relations)

        # 3. save scores.csv
        with open(os.path.join(graph_dir, "scores.csv"), mode='w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=["relation_id", "score"])
            writer.writeheader()
            writer.writerows(scores)

        return graph_dir
