"""Create fiscal period management tables (idempotent).

Run: python migrations/add_fiscal_period_tables.py
"""
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from app.core.database import engine
from app.models.fiscal_period import (
    FiscalYear,
    FiscalPeriod,
    PeriodEndStatement,
    PeriodCloseChecklist,
)


def run():
    tables = [
        FiscalYear.__table__,
        FiscalPeriod.__table__,
        PeriodEndStatement.__table__,
        PeriodCloseChecklist.__table__,
    ]
    for table in tables:
        table.create(bind=engine, checkfirst=True)
        print(f"OK: {table.name}")
    print("Fiscal period tables migration complete.")

    # Bootstrap fiscal years for existing installs
    try:
        from app.core.database import SessionLocal
        from app.models.company import Company
        from app.models.branch import Branch
        from app.services.fiscal_period_service import FiscalPeriodService

        db = SessionLocal()
        try:
            if db.query(FiscalYear).count() == 0:
                service = FiscalPeriodService(db)
                companies = db.query(Company).all()
                if companies:
                    for company in companies:
                        hq = db.query(Branch).filter(
                            Branch.company_id == company.id,
                            Branch.is_head_office == True,
                        ).first()
                        branch = hq or db.query(Branch).filter(
                            Branch.company_id == company.id
                        ).first()
                        service.bootstrap_default_fiscal_year(
                            branch_id=branch.id if branch else None,
                            start_month=getattr(company, "fiscal_year_start_month", 1) or 1,
                            activate=True,
                        )
                        print(f"Bootstrapped fiscal year for company {company.name}")
                else:
                    service.bootstrap_default_fiscal_year(activate=True)
                    print("Bootstrapped default fiscal year (no company)")
        finally:
            db.close()
    except Exception as exc:
        print(f"Note: fiscal year bootstrap skipped: {exc}")


if __name__ == "__main__":
    run()
