import uuid
from datetime import datetime
from app.extensions import db


class Report(db.Model):
    __tablename__ = "reports"

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
    project_name = db.Column(db.String(500), nullable=False)
    project_description = db.Column(db.Text, nullable=False)
    language = db.Column(db.String(5), default="ar")
    market_analysis = db.Column(db.JSON, nullable=True)
    financial_analysis = db.Column(db.JSON, nullable=True)
    competitive_analysis = db.Column(db.JSON, nullable=True)
    synthesis_result = db.Column(db.JSON, nullable=True)
    full_report_html = db.Column(db.Text, nullable=True)
    verdict = db.Column(db.String(50), nullable=True)
    share_token = db.Column(db.String(64), unique=True, nullable=True, index=True)
    is_public = db.Column(db.Boolean, default=False)
    custom_sections = db.Column(db.JSON, nullable=True)
    user_note = db.Column(db.Text, nullable=True)  # User's note for AI to consider during regeneration
    report_references = db.Column(db.JSON, nullable=True)  # Sources/references for the report data
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    @property
    def viability_score(self):
        if isinstance(self.synthesis_result, dict):
            score = self.synthesis_result.get("viability_score") or self.synthesis_result.get("score")
            if score is not None:
                try:
                    return int(score)
                except (ValueError, TypeError):
                    pass
        return None

    def generate_share_token(self):
        self.share_token = uuid.uuid4().hex
        return self.share_token


class ReportNotebook(db.Model):
    """Links a Report to a Google NotebookLM notebook."""
    __tablename__ = "report_notebooks"

    id = db.Column(db.Integer, primary_key=True)
    report_id = db.Column(db.Integer, db.ForeignKey("reports.id"), nullable=False, unique=True)
    notebook_id = db.Column(db.String(255), nullable=False)
    source_id = db.Column(db.String(255), nullable=True)
    notebook_url = db.Column(db.String(1000), nullable=True)
    nlm_account_id = db.Column(db.Integer, db.ForeignKey("nlm_admin_accounts.id"), nullable=True)  # Admin account used
    mode = db.Column(db.String(20), default="notebooklm")  # notebooklm, rag
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    report = db.relationship("Report", backref=db.backref("notebook", uselist=False))


class NotebookAsset(db.Model):
    """A generated asset (audio, video, quiz, etc.) from NotebookLM."""
    __tablename__ = "notebook_assets"

    ASSET_TYPES = [
        "audio", "video", "mind_map", "report",
        "flashcards", "quiz", "infographic", "slide_deck",
    ]

    id = db.Column(db.Integer, primary_key=True)
    report_id = db.Column(db.Integer, db.ForeignKey("reports.id"), nullable=False)
    notebook_ref_id = db.Column(db.Integer, db.ForeignKey("report_notebooks.id"), nullable=True)
    asset_type = db.Column(db.String(30), nullable=False)
    asset_index = db.Column(db.Integer, default=1, nullable=False)  # For multiple assets of same type
    status = db.Column(db.String(20), default="pending")  # pending / generating / ready / failed
    file_path = db.Column(db.String(500), nullable=True)
    file_format = db.Column(db.String(10), nullable=True)  # mp3, mp4, pdf, png, json, md
    error_message = db.Column(db.Text, nullable=True)
    metadata_json = db.Column(db.JSON, nullable=True)
    share_token = db.Column(db.String(64), unique=True, nullable=True, index=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    completed_at = db.Column(db.DateTime, nullable=True)

    report = db.relationship("Report", backref=db.backref("notebook_assets", lazy="dynamic"))
    notebook_ref = db.relationship("ReportNotebook")
