import pytest
import json
import os


class TestProjects:
    """Test project-related functionality."""

    def test_project_list(self, logged_in_client):
        """Test listing projects."""
        response = logged_in_client.get("/projects/")
        assert response.status_code == 200

    def test_create_project(self, logged_in_client, app):
        """Test creating a new project."""
        response = logged_in_client.post(
            "/projects/create",
            data={
                "codigo": "TEST123",
                "descripcion": "Proyecto de Prueba",
                "cliente": "Cliente Test",
                "esquema": "TEST001",
                "destinacion": "Pruebas",
                "notas": "Notas de prueba",
            },
            follow_redirects=True,
        )

        assert response.status_code == 200

        # Check if project was created in storage
        with app.app_context():
            # Check indices
            indices_path = os.path.join(app.config["STORAGE_PATH"], "indices.json")
            with open(indices_path, "r") as f:
                indices = json.load(f)
                assert indices["max_project_id"] > 0

    def test_view_project(self, logged_in_client, app):
        """Test viewing a project (requires creating one first)."""
        # Create a project first
        logged_in_client.post(
            "/projects/create",
            data={
                "codigo": "TEST456",
                "descripcion": "Proyecto para visualizar",
                "cliente": "Cliente Test",
                "esquema": "TEST001",
                "destinacion": "Pruebas",
                "notas": "Notas de prueba",
            },
            follow_redirects=True,
        )

        # Now find the project ID
        with app.app_context():
            projects_dir = os.path.join(app.config["STORAGE_PATH"], "projects")
            project_dirs = os.listdir(projects_dir)
            assert len(project_dirs) > 0

            # Get first project directory
            project_dir = project_dirs[0]
            project_id = project_dir.split("_")[0].replace("@", "")

            # Try to view it
            response = logged_in_client.get(f"/projects/{project_id}")
            assert response.status_code == 200
            assert b"Proyecto para visualizar" in response.data

    def test_edit_project(self, logged_in_client, app):
        """Test editing a project."""
        # Create a project first
        logged_in_client.post(
            "/projects/create",
            data={
                "codigo": "TESTEDIT",
                "descripcion": "Proyecto para editar",
                "cliente": "Cliente Test",
                "esquema": "TEST001",
                "destinacion": "Pruebas",
                "notas": "Notas originales",
            },
            follow_redirects=True,
        )

        # Find the project ID
        with app.app_context():
            projects_dir = os.path.join(app.config["STORAGE_PATH"], "projects")
            project_dirs = [d for d in os.listdir(projects_dir) if "TESTEDIT" in d]
            assert len(project_dirs) > 0

            project_dir = project_dirs[0]
            project_id = project_dir.split("_")[0].replace("@", "")

            # Edit the project
            response = logged_in_client.post(
                f"/projects/{project_id}/edit",
                data={
                    "codigo": "TESTEDIT",
                    "descripcion": "Proyecto editado",
                    "cliente": "Cliente Test Modificado",
                    "esquema": "TEST001",
                    "destinacion": "Pruebas Modificadas",
                    "notas": "Notas modificadas",
                },
                follow_redirects=True,
            )

            assert response.status_code == 200
            assert b"Proyecto editado" in response.data
