"""
models/project.py
A project contains one or more transcripts and a coding framework.
The framework is stored as JSONB — built from client_themes at creation time.
New fields: org_name, manager_name, manager_email, phone, description,
            file_count, client_themes
"""
import uuid
from datetime import datetime
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey, Enum as SAEnum
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.orm import relationship
from app.database import Base
import enum


class ProjectStatus(str, enum.Enum):
    draft      = "draft"
    processing = "processing"
    complete   = "complete"
    failed     = "failed"


class Project(Base):
    __tablename__ = "projects"

    id           = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    workspace_id = Column(UUID(as_uuid=True), ForeignKey("workspaces.id"), nullable=False)
    owner_id     = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)

    # Core fields
    name         = Column(String, nullable=False)
    domain       = Column(String, nullable=True)

    # Client intake fields
    org_name      = Column(String, nullable=True)
    manager_name  = Column(String, nullable=True)
    manager_email = Column(String, nullable=True)
    phone         = Column(String, nullable=True)
    description   = Column(String, nullable=True)
    file_count    = Column(Integer, nullable=True, default=1)

    # Themes as entered by client — stored as JSON list
    # [{"group": "FACILITATORS", "description": "...", "themes": ["theme1", "theme2"]}, ...]
    client_themes = Column(JSONB, nullable=True)

    # framework = coding framework string fed into the pipeline
    # auto-built from client_themes at project creation
    framework    = Column(JSONB, nullable=True)

    # Pre-generated file paths — set after pipeline completes (instant download)
    report_path  = Column(String, nullable=True)   # /data/uploads/{project_id}/report.docx
    excel_path   = Column(String, nullable=True)   # /data/uploads/{project_id}/report.xlsx

    status       = Column(SAEnum(ProjectStatus), default=ProjectStatus.draft)
    created_at   = Column(DateTime, default=datetime.utcnow)
    updated_at   = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    workspace    = relationship("Workspace", back_populates="projects")
    owner        = relationship("User", back_populates="projects")
    transcripts  = relationship("Transcript", back_populates="project", cascade="all, delete-orphan")
    code_results = relationship("CodeResult", back_populates="project", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<Project {self.name} [{self.status}]>"